繁体   English   中英

从.txt文件C++中获取多于一行

[英]Getting more than one line from .txt file C++

我想从 data.txt 文件中提取不止一行。 我只能拿第一个。 我尝试使用 while 循环,但在这种情况下我似乎不知道如何使用它。

用while循环编辑:

#include <iostream>
#include <fstream>

using namespace std;

int zapis()
{
    fstream file;
    string text;

    file.open("data.txt", ios::app);
    cout << "Type in text that you would like to store: ";
    getline(cin, text);
    file << text << endl;
    file.close();

    return 0;
}

int odczyt()
{
    fstream file;
    string line;
    int nr_lini = 1;

    file.open("data.txt", ios::in);
    if(file.good()==false)
    {
        cout << "Error occured!";
    }
    else
    {
        while(getline(file, line))
           {
               getline(file, line);
               cout << line;
           }
    }
    file.close();

    return 0;
}

int main()
{
    zapis();
    odczyt();

    return 0;
}

为什么在你的循环中调用 getline两次 还要注意分号

 while(getline(file, line));
                           ^

你认为那里的分号有什么作用?

这是对的

while (getline(file, line))
{
    cout << line;
}

您的代码是正确的,只需遍历文件即可。 此外,您可以将 function 设为void ,因为它始终returns 0 ,而您对返回值不做任何事情。

void odczyt(){

    fstream file;
    string line;

    file.open("data.txt", ios::in);
    if(!file.good())
    {
        cout << "Error occured!";
    }
    else
    {
        while(getline(file, line);) {  // while text file still has lines, you write the line and read next
            cout << line;
        }
    }
    file.close();
}

暂无
暂无

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

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