简体   繁体   English

C ++逐行读取但无法逐行显示输出

[英]c++ reading line by line but not able to show output line by line

I am trying to run a C++ code. 我正在尝试运行C ++代码。 My input file has number of lines and I am trying remove the spaces in each line and then display. 我的输入文件有几行,我尝试删除每行中的空格,然后显示。 But, when i run the code the output is coming in a single line ie all thelines of the file are being shown in one single line. 但是,当我运行代码时,输​​出显示在一行中,即文件的所有行都显示在一行中。

Please solve my problem , so that i get the output line by line. 请解决我的问题,以便我逐行获取输出。

Thanks. 谢谢。

I have tried this code. 我已经尝试过此代码。 This is my code: 这是我的代码:

int main()
{
    int i = 0, len, j;
    std::string str;
    ifstream iFile("g.txt");
    while (std::getline(iFile, str) != 0)
    {
        len = str.length();
        for (i = 0; i < len; i++)
        {
            if (str[i] == ' ')
            {
                for (j = i; j < len; j++)
                {
                    str[j] = str[j + 1];
                }
                len--;
            }
        }
        cout << str;
    }
}

cout<<str; is going to write the string to the output buffer and that is it. 将字符串写入输出缓冲区,就是这样。 The next time you call it the str you write out will start right after that last str that was written. 下次调用它时,您写出的str将在最后写入的str之后立即开始。 If you want each str on its own line then you can use 如果您希望每个str位于自己的行上,则可以使用

cout << str << endl;
//or
cout <<str << "\n";

The reason each line does not retain its newline character is that getline() reads until it encounters a newline and then stores everything up to that newline in the string. 每行不保留其换行符的原因是getline()读取直到遇到换行符,然后将所有内容存储到字符串中。 It then tosses that newline out instead of adding it to the string. 然后,它抛出该换行符,而不是将其添加到字符串中。

You are writing like this: 您正在这样编写:

cout<<str;

You need to output the new-line after your string, which is done as follows: 您需要在字符串之后输出换行符,操作如下:

cout<<str<<endl;

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

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