簡體   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