从.txt文件C++中获得多行

从.txt文件C++中获得多行,c++,C++,我想从data.txt文件中提取多行内容。我只能拿第一个。我尝试使用while循环,但似乎我不知道在这种情况下如何使用它 使用while循环编辑: #include <iostream> #include <fstream> using namespace std; int zapis() { fstream file; string text; file.open("data.txt", ios::app); 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;
}

您的代码是正确的,只需在文件中循环。此外,还可以使函数无效,因为它总是返回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();
}
为什么在循环中调用getline两次?还要注意分号

 while(getline(file, line));
                           ^
你认为分号有什么作用

这是正确的

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

请在file.open和file.close之间执行循环。请显示您对while循环的尝试。当我们知道你面临什么问题时,帮助就容易多了。另请看:你做过任何研究吗?应该很容易找到如何从文件中读取行的示例。谢谢,在我以前的尝试之后,我忘记删除这个int。我收到以下错误:错误:无法将'line'从'std::uuCxx11::string'{aka'std::uuCxx11::basic_string'}转换为'bool'。john非常感谢。真管用@约翰,我的错,打字错误,谢谢,我想做什么。