four names are being printed

hi guys when I try to print out each name,name : with a blank name gets printed,so 4 lines get printed instead of three,

how can I avoid this?

I tried adding get() to get the newline character but it didn't discard it,still prints the a new line with a blank name

maybe I am writing a blank space to my file,if so where does this happen,and how can I avoid it in the future? thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  list<string> myList;

	myList.push_back("adam");
	myList.push_back("bill");
	myList.push_back("steve");


	ofstream output;
	string fileName("STD.txt");

    output.open(fileName);

    for(list<string>::iterator it = myList.begin(); it != myList.end(); it++){

        output << *it;
        output << endl;

       }

    output.close();

    list<string> secondList;

    ifstream input;
    input.open(fileName);

    while(input){

    	string line;
    	input >> line;
    	cout << "name : " << line;
    	cout << endl;
    	input.get();
    	if(!input){

    		break;
    	}
    }
   input.close();

}
Line 30 will discard the NL. Therefore at line 33, you're eating the first character of the next name.

Line 30: You fail to check if the input operation succeeded. Your loop should look like the following:

1
2
3
4
5
6
    string line;
    while (input >> line)
    {  //  Input operation succeeded
        cout << "name : " << line;
    	cout << endl;
    }

Last edited on
thanks Anon =)
Hi Anon when I try to add each name I get from line it seems to cut off the first name "adam" with the code I used

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

 list<string> secondList;

    ifstream input;
    input.open(fileName);
    string line;

    while(input >> line){

    	
    	input >> line;
    	secondList.push_back(line);
    	
    }
    for(list<string>::iterator it = secondList.begin(); it != secondList.end(); it++){

         cout << * it << endl;
     }

   input.close();

}


Line 11 is redundant. Remove it. You're trying to read from the file twice each time through the loop.
thanks Anon that worked =)
Topic archived. No new replies allowed.