【发布时间】:2019-01-18 00:24:44
【问题描述】:
我需要输入一定数量的字符串,每一个都输入一个新行。当我尝试在循环中使用 getline() 时,它会输入第一个字符串,然后立即结束。
这是我要解决的问题,您可以在其中看到我要使用的输入样式: https://wcipeg.com/problem/ccc98s1
我查看了 cin.ignore() 来解决问题,但我似乎无法让它正常工作。
int n;
cin >> n;
for(int i = 0; i < n; i++) {
string input;
getline(cin, input);
cout << "Line Entered: " << input << endl;
}
如果 n 输入 2,然后尝试在不同的行中输入两个字符串,则不起作用。
【问题讨论】:
-
请出示您的代码。您还希望我们如何帮助发现错误?
-
刚刚添加了一些示例代码
-
这对我有用:onlinegdb.com/B1yqWiCf4
-
@EvanWild 帮助您继续前进,您可以在大约 4 行代码中完成此操作。如果您使用
while (getline (std::cin, line))阅读,则只需创建一个stringstream来阅读每个单词,检查其length,然后检查find和replace,例如std::string word; std::stringstream s (line); while (s >> word) if (word.length() == 4) line.replace (line.find (word, 0), 4, repl);(事先定义了const std::string repl = "****";)