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

时间:2015-10-16 02:55:20

标签: c++ file stdin cin io-redirection

所以我试图

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包含一行&#34;你好&#34;)

用户输入似乎工作正常

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

编辑:我的问题是,如何终止此循环会计用户输入和重定向?

2 个答案:

答案 0 :(得分:1)

好吧,在第一种情况下不推荐使用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;
}

答案 1 :(得分:1)

#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块中永远不会为true,因为如果cin.eof()为真,那么返回getline的{​​{1}}表达式转换为bool的转换为false,从而结束循环。

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