简体   繁体   English

从bash管道输入文件,并使用getline(cin,line)逐行读取它

[英]piping input file from bash and read it line by line using getline(cin,line)

I am trying to read the file using getline() function and piping my input file using bash command but get illogical output. 我试图使用getline()函数读取文件,并使用bash命令管道输入文件,但输出不合逻辑。

This is my main.cpp code: 这是我的main.cpp代码:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;
int main(int argc, const char * argv[]) {

    string line;

    while(getline(cin,line)){
        cout<<line<<endl;
    }
    return 0;
}

My input file named input.txt look like this 我的输入文件名为input.txt看起来像这样

4 MF MF FM FF MF MM
MM FF
MF MF MF MF FF

My bash command and running result 我的bash命令和运行结果

DENGs-MacBook-Pro:APS stevedeng$ g++ -o main main.cpp -std=c++11
DENGs-MacBook-Pro:APS stevedeng$ ./main < input.txt
MF MF MF MF FFMF MM

What I thought is that the program will read the input.txt line by line and print the output exactly as the format as the input file. 我认为该程序将逐行读取input.txt并按照与输入文件相同的格式打印输出。

Can someone explain what is happening here with the only one line of wired looking output? 有人可以用仅一行的有线输出来解释这里发生了什么吗?

How can I achieve the result of reading it line by line if the only way I can do is piping the input file from bash instead of using ifstream ? 如果我唯一能做的就是从bash用管道输送输入文件而不是使用ifstream,如何实现逐行读取结果? Any help will be appreciated. 任何帮助将不胜感激。

It seems as if your terminal does not receive or neglect the line feed, such that every new line overwrites the previously written one. 似乎您的终端没有收到或忽略换行符,因此每一行都将覆盖先前写入的行。

One thing could be that the input file contains only the carriage return but now line feed, and for some reason getline does not correct this. 一件事可能是输入文件仅包含回车符,但现在包含换行符,由于某种原因, getline不能更正此问题。 If this is the issue, see the following answer on SO (please don't forget to upvote if helpful). 如果这是问题所在,请参阅SO的以下答案(如果有帮助,请不要忘记投票)。

Another thing could be that the line feed is not written to cout . 另一件事可能是换行符未写入cout I'd suggest - at least for diagnostic purpose - to try printf("%s\\r\\n",line.c_str()) . 我建议-至少出于诊断目的-尝试使用printf("%s\\r\\n",line.c_str())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM