如何使用户输入多行

How To Make User Input Multiple Lines

本文关键字:输入 用户 何使      更新时间:2023-10-16

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

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

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

这些是用户输入的输入

篮球 棒球 足球//1号线

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

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

为什么不在 while 循环中使用std::getline,这样一旦进入空行,循环就会退出,如下所示:

#include <iostream>
#include <string>
#include <vector>
int main() {
std::string line;
std::vector<std::string> lines;
while (getline(std::cin, line) && !line.empty()) {
lines.push_back(line);
}
std::cout << "User has entered " << lines.size() << " lines" << std::endl;
for (auto const& l : lines) {
std::cout << l << std::endl;
}
std::cout << "... End of program ..." << std::endl;
return 0;
}

您可以将用户输入到std::vector容器中的每行存储起来,并在以后再次检索这些行。

可能的输出:

First line
Second line
User has entered 2 lines
First line
Second line
... End of program ...

更新

如果你想让用户只输入 2 行,如果你想使用 for 循环,那么你可以这样做:

#include <iostream>
#include <string>
#include <vector>
int main() {
std::string line;
std::vector<std::string> lines;
for (int i = 0; i < 2; i++) {
std::getline(std::cin, line);
lines.push_back(line);
}
std::cout << "User has entered " << lines.size() << " lines" << std::endl;
for (auto const& l : lines) {
std::cout << l << std::endl;
}
std::cout << "... End of program ..." << std::endl;
return 0;
}

输出可以是:

First line                                                                                                                                                                         
Second line                                                                                                                                                                        
User has entered 2 lines                                                                                                                                                           
First line                                                                                                                                                                         
Second line                                                                                                                                                                        
... End of program ...