如何使用户输入多行

问题描述 投票:0回答:1

我想使用户能够输入多行字符串。我一直在尝试for循环,但到目前为止只返回了最后一行。

例如,用户输入以下字符串和行。string str;getline(cin, str);

或循环for(i=0;i<n;i++){getline(cin, str);}

这些是用户输入的输入

篮球棒球足球//第1行

曲棍球足球拳击” //第2行

现在,我希望能够一次返回这两行。我不知道该怎么做。另外,我发现更困难的是试图弄清楚用户是否只能输入一行,两行或三行。我知道如何用cases点缀帽子,但是我现在想知道是否有一种更简单的方法看起来不那么混乱,

c++ loops input cin getline
1个回答
0
投票

为什么不在这样的while循环中使用std::getline

#include <iostream>
#include <string>

int main() {
    std::string line;
    size_t line_counter = 0;

    while (getline(std::cin, line) && !line.empty()) {
        line_counter++;
        std::cout << line_counter << ". line: " << line << std::endl;
    }


    std::cout << "... End of program ..." << std::endl;
    return 0;
}

一旦输入空行,循环就会停止。

可能的输出:

First line
1. line: First line
Second line
2. line: Second line

... End of program ...
© www.soinside.com 2019 - 2024. All rights reserved.