如何让用户输入多行
How To Make User Input Multiple Lines
我想让用户能够输入多行字符串。我一直在尝试使用 for 循环,但到目前为止只有最后一行是 returned.
例如,用户输入以下字符串和行。
string str;
getline(cin, str);
或者循环
for(i=0;i<n;i++){
getline(cin, str);}
这些是用户输入的内容
Basketball Baseball Football //line 1
Hockey Soccer Boxing" //line 2
现在,我希望能够同时 return 这两行。我不知道该怎么做。
此外,我发现更困难的是试图弄清楚用户是否只输入一行、两行或三行。我知道如何用 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 ...
我想让用户能够输入多行字符串。我一直在尝试使用 for 循环,但到目前为止只有最后一行是 returned.
例如,用户输入以下字符串和行。
string str;
getline(cin, str);
或者循环
for(i=0;i<n;i++){
getline(cin, str);}
这些是用户输入的内容
Basketball Baseball Football //line 1
Hockey Soccer Boxing" //line 2
现在,我希望能够同时 return 这两行。我不知道该怎么做。
此外,我发现更困难的是试图弄清楚用户是否只输入一行、两行或三行。我知道如何用 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 ...