0

I have a file with this format:

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

The first line is the number of lines, so I can make a loop to read the file with the number of lines. For the other lines, I would like to read the file line by line and store the data until I get a "0" on the line that's why there is a 0 at the end of each line. The first column is the task name. The others columns are the constraints name.

I tried to code something but It doesn't seem to work

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");
};

The "0" represents the end of the constraints for a task.

I think my code doesn't work properly because the constraint 10 for the task 4 contains a "0" too.

Thanks in advance for your help

Regards

Killzone Kid
  • 6,171
  • 3
  • 17
  • 37
Toms lns
  • 39
  • 8

1 Answers1

0

The problem is that you are reading individual characters from the file, not reading whole integers, or even line-by-line. Change your currentTask and currentConstraint variables to int instead of char, and use std::getline() to read lines that you then read integers from.

Try this:

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;
}

Live Demo

That being said, the terminating 0 on each line is unnecessary. std::getline() will stop reading when it reaches the end of a line, and operator>> will stop reading when it reaches the end of the stream.

Live Demo

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • I see what you did, you just read until the end of the line, instead of reading until a 0. And we only take constraints different from 0. Thanks for your help – Toms lns May 08 '18 at 21:34