【问题标题】:How do I read from cin until it is empty?我如何从 cin 读取直到它为空?
【发布时间】:2021-09-23 10:16:11
【问题描述】:

我正在尝试从通过 cin 传入的文件中读取成对的行。 我需要阅读直到文件为空。 如果一对中的一行是空的,我需要将该行保存为“”。 如果两行都是空的,那么都需要保存并处理为“”。

我正在使用 getline 读取其中的行,并使用一个 while 循环继续进行,直到两行都为空。 但是,我需要它一直持续到文件为空,因为有可能 2 个空行后跟许多填充行。

这就是我现在的样子:

getline(cin, str1); getline(cin, str2);
while (str1 == "" | str1 != "") {
  ....
  str1 = ""; str2 = "";
  getline(cin, str1); getline(cin, str2);
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    如果文件连续包含两个换行符,这将不起作用。您可以使用cin.eof() 来检查您何时到达文件末尾。如果它返回 1,则说明您试图读取文件末尾之外的内容。

    【讨论】:

      【解决方案2】:

      如果您从文件中获取输入并将其传递给您的 c++ 编译程序

      cat input_file.txt | cpp_binary_executable
      

      那么cin在while循环中会读取每一行直到文件结束

          string temp;
          while (cin >> temp) //read each line till the end of file
          {
              cout << temp << endl;
          }
      

      【讨论】:

        【解决方案3】:

        惯用的方式是:

        while (getline(cin, str1) && getline(cin, str2)) {
            // ...
        }
        

        甚至:

        while (getline(getline(cin, str1), str2)) {
            // ...
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-09-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-28
          • 1970-01-01
          • 2017-05-22
          • 2012-12-22
          相关资源
          最近更新 更多