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

标签 c++ file stdin cin io-redirection

所以我正在尝试要么

a) 允许用户输入一个字符串,直到他们输入退出

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 是因为在实际程序中我需要逐行读取文件,然后在移动到文件的下一行之前操作该行

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

最佳答案

#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 block 内永远不会为真,因为 if cin.eof()为真,则 getline返回 cin 的表达式转换为 bool 将转换为 false,从而结束循环。

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

关于c++ - 如何期望来自重定向和用户输入的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33161812/

相关文章:

java - 运行 JavaCpp 示例时出现 UnsatisfiedLinkException (LegacyLibrary)

c++ - 预先估计输出的 dll/exe 的大小?

Python - 如何在替换字符串后保存保存文件

java - InputStream read(byte[] b, int off, int len) - 删除文件的其余部分?

python - 在没有 paramiko 的情况下通过 python 运行 ssh 时为 "Pseudo-terminal will not be allocated because stdin is not a terminal"

c stdin 二维数组文件输入

c++ - const 枚举或其他

c++ - 将资源锁定对象作为参数传递

JavaScript - 更新变量以不断更改文件内容

php - 如何检查 bash 输入是否被重定向到 PHP 脚本?