簡體   English   中英

用特定數據逐行讀取文件C ++

[英]Read a file line by line with specific data C++

我有一個具有這種格式的文件:

11
1 0
2 8 0
3 8 0
4 5 10 0
5 8 0
6 1 3 0
7 5 0
8 11 0
9 6 0
10 5 7 0
11 0

第一行是行數,因此我可以進行循環以讀取具有行數的文件。 對於其他各行,我想逐行讀取文件並存儲數據,直到在該行上獲得“ 0”為止,這就是每行末尾都有0的原因。 第一列是任務名稱。 其他列是約​​束名稱。

我嘗試編寫一些代碼,但似乎不起作用

printf("Constraints :\n");
for (int t = 1; t <= numberofTasks; t++) 
{
    F >> currentTask;
    printf("%c\t", currentTask);
    F >> currentConstraint;
    while (currentConstraint != '0') 
    {
        printf("%c", currentConstraint);
        F >> currentConstraint;
    };
    printf("\n");
};

“ 0”表示任務約束的結尾。

我認為我的代碼無法正常工作,因為任務4的約束10也包含“ 0”。

在此先感謝您的幫助

問候

問題在於您正在從文件中讀取單個字符,而不是讀取整個整數,甚至不逐行讀取。 currentTaskcurrentConstraint變量更改為int而不是char ,並使用std::getline()讀取行,然后從中讀取整數。

嘗試這個:

F >> numberofTasks;
F.ignore();

std::cout << "Constraints :" << std::endl;
for (int t = 1; t <= numberofTasks; ++t) 
{
    std::string line;
    if (!std::getline(F, line)) break;

    std::istringstream iss(line);

    iss >> currentTask;
    std::cout << currentTask << "\t";

    while ((iss >> currentConstraint) && (currentConstraint != 0))
    {
        std::cout << currentConstraint << " ";
    }

    std::cout << std::endl;
}

現場演示

話雖如此,在每行上都不需要以0結尾。 std::getline()到達行尾時將停止讀取,而operator>>到達流尾時將停止讀取。

現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM