Simple writing file problem

Hey guys, I would like to write 5 lines to a text file, and if I enter "stop", the program should terminate. It works, however "stop" is written to the text file as well. This tells me that the "else" code is run after I type "stop", can't figure why.

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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string word;
	
ofstream outfile; // Create an input filestream
outfile.open("abcd.txt"); // Open a file for output


for(int i=0; i < 5; i++)
{
	
	if(word=="stop")
	{
		i=4;
	}
	else
	{	
	getline(cin, word);
	outfile <<word<<endl;
	}
}

outfile.close(); // Close file 
return 0;
}
Something like
while(word != "stop")
Might be a little better.
You are setting i to 4 which allows the for loop to run again, set i to 5 to stop the loop.
You are setting i to 4 which allows the for loop to run again, set i to 5 to stop the loop.


Tried that, doesn't work.
I didnt look closely enough
1
2
getline(cin, word);
outfile <<word<<endl;
you are outputting to the file right after the input of the word. Try moving getline() out of the if-else block.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for(int i=0; i < 5; i++)
{
	getline(cin, word);

	if(word=="stop")
	{
		i=5;
	}
	else
	{	
	
	outfile <<word<<endl;
	}
}
Last edited on
Thanks naraku, it works now, but I don't understand the difference. Before, why did the 'stop' appear in the output, even though the else code wasn't used for it?
Like I said, you output the word right after it is input and before it is checked by the if statement.
Topic archived. No new replies allowed.