A quick question about while loops

I'm just curious about how exactly a simple input file will be effected by a while loop.

For example I have a file that lists a number, followed by a group of names and numbers related to them with an ending line of -1

7
bill 5
sarah 7
okabe 3
-1
5
tim 6
rebecca 9
alice 92
-1

If I had a loop of say...

1
2
3
4
5
  while (! endOfInput) //loop 1
{
   readCalcNumber //function to use first number
    while ( input != -1){do stuff with the names and numbers} //loop 2
}



would the code after exiting loop 2 and reentering loop 1 automatically begin at the 5 for the next set of data, or would it begin reading it at Bill since they were part of two seperate loops?
Last edited on
It would start reading at Bill because they are 2 separate loops.
Last edited on
That's what I was afraid of, and would explain why I was having trouble then. Then perhaps a recursive function would work better?

something like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

void doStuff(input)
{
// insert code that does stuff to the number
// insert code that does stuff to the name

if (input !<0) 
      doStuff(input);
else return;
}
void main()
{

//code to set things up
 while (! endOfInput) //loop 1
 {
   readCalcNumber //function to use first number
   doStuff(input);
 }
}


Something like this would just have it continue reading down the line of the input in the same while loop, so that when the recursion ends the loop should begin again at 5, or am I missing the mark again?
Last edited on
There is no need for a recursive function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::string str, temp;

    std::ifstream file;
    file.open("filename");

    while (std::getline(file, temp))
    {
        str += temp + "\n";
    }

    std::cout << str << std::flush;

    return 0;
}
Would getLine actually work though? I thought it grabs the whole line, But I need the data separately.

Like if it reads
6
1 Sam I Am
5 Leif Me Be
-1
9
7 Sam I Am
2 Leif Me Be
-1

I need to use 7 for a calculation, and then use Sam I Am to find his information and apply the calculation to Sams info. and then on the next line to do a calculation with 8 and apply it to Leif's profile.

but I need that to be in another loop because the 6 applies to Sam and lief in the first set, and the 9 applies to them in the second set.

Update, I tried the recursive idea I had and it works like a charm, all the date is read in safely and assigned to the correct datatypes. I think this is the structure I'll keep for this particular issue but I am curious if there are other ways to handle this particular problem.
Last edited on
Topic archived. No new replies allowed.