![](/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.