如何期望来自重定向和用户输入的输入

How to expect input from redirection and user input

所以我正在尝试

a) 允许用户输入字符串,直到他们键入 exit

b) 从标准输入(a.out < test.txt)重定向文件直到文件末尾然后终止

我对代码的尝试:

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int main(){

    string input = "";
    while(true){
       cout << "Enter string: ";
       while(getline(cin, input)){
       if(input == "exit" || cin.eof()) goto end;
       cout << input << "\n";
       cout << "Enter string: ";                       
     }

    }
    end:
    return 0;



}

这会导致重定向问题,当我使用命令 a.out < test.txt 时出现无限循环(其中 test.txt 包含一行 "hello")

用户输入似乎工作正常

我使用 getline 是因为在实际程序中我需要逐行读取文件,然后在移动到文件的下一行之前操作该行

编辑:我的问题是,如何终止这个循环来考虑用户输入和重定向?

嗯,在第一种情况下不建议使用 goto,您可以使用布尔数据类型来实现您的目标:

int main(){
bool flag = true;

string input = "";
while(flag){
    cout << "Enter string: ";
    while(getline(cin, input)){
        if(input == "exit" || cin.eof()) {
            flag = false;
            break;
        }
        cout << input << "\n";
        cout << "Enter string: ";
    }

  }


 return 0;
}
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int main(){
  string input = "";
  while(cin && cout<<"Enter string: " && getline(cin, input)){
    //check both cout and cin are OK with the side effect of
    // writing "Enter string" and reading a line

    if(input == "exit") return 0; //no need for a goto
    cout << input << "\n";
  }
  if(cin.eof()) return 0; //ended because of EOF
  return 1; //otherwise, the loop must have broken because of an error
}

保持简单。您不需要外部循环,并且 cin.eof() 在 while 块内永远不会为真,因为如果 cin.eof() 为真,则 getline 表达式 returns cin 转换为 bool 将转换为 false,从而结束循环。

如果 cin 遇到 EOF 或错误,则循环结束。