![](/img/trans.png)
[英]Read data from file and sum over specific columns after hitting specific line (string) using 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”。
在此先感謝您的幫助
問候
問題在於您正在從文件中讀取單個字符,而不是讀取整個整數,甚至不逐行讀取。 將currentTask
和currentConstraint
變量更改為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.