【问题标题】:How to expect input from redirection and user input如何期望来自重定向和用户输入的输入
【发布时间】:2015-10-16 02:55:19
【问题描述】:

所以我正在尝试

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 &lt; test.txt 时,我得到一个无限循环(其中 test.txt 包含一行“hello”)

用户输入似乎工作正常

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

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

【问题讨论】:

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


【解决方案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 块内永远不会为真,因为如果cin.eof() 为真,那么返回cingetline 表达式转换为布尔值将转换为假,从而结束循环。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2012-05-01
      • 2011-07-09
      • 2012-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-02
      • 2016-11-16
      • 1970-01-01
      相关资源
      最近更新 更多