【问题标题】:How to force getline() to input one line at a time [duplicate]如何强制getline()一次输入一行[重复]
【发布时间】: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,然后检查findreplace,例如std::string word; std::stringstream s (line); while (s &gt;&gt; word) if (word.length() == 4) line.replace (line.find (word, 0), 4, repl);(事先定义了const std::string repl = "****";

标签: c++ string input getline


【解决方案1】:
int n;
cin >> n;
cin.ignore(); // are you sure you tried this?

for(int i = 0; i < n; i++) {
    string input;
    getline(cin, input);
    cout << "Line Entered: " << input << endl;
}

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 2023-04-01
    • 2012-11-12
    • 2019-06-14
    • 1970-01-01
    • 2018-12-02
    • 2011-10-02
    • 1970-01-01
    • 2018-08-19
    相关资源
    最近更新 更多