Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 逐行读取带有特定数据C++;_C++_File_Stream - Fatal编程技术网

C++ 逐行读取带有特定数据C++;

C++ 逐行读取带有特定数据C++;,c++,file,stream,C++,File,Stream,我有一个以下格式的文件: 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 <

我有一个以下格式的文件:

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");
};
printf(“约束:\n”);
对于(int t=1;t>currentTask;
printf(“%c\t”,当前任务);
F>>电流约束;
而(currentConstraint!=“0”)
{
printf(“%c”,currentConstraint);
F>>电流约束;
};
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;
}
F>>任务数;
F.忽略();

STD::请编辑你的问题,包含“编辑你的问题要包含什么”?你不明白哪个词?为什么混合流?或者坚持C++ I/O(<代码>运算符> <代码>)或使用C I/O流(<代码> Prtff<代码>)。我建议您使用
std::getline
std::string
读入一行文本。您可以使用
std::istringstream
读入字符串中的数字。我明白了您所做的,您只需一直读到行尾,而不是一直读到0。我们只接受与0不同的约束。感谢您的帮助