How can i loop through a txt file?

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
bool gameOn;
string str;
int n = 0;
while (gameOn)
  {
    cin>>str;
    if(str=="save")
    {
      ofstream test("Save.txt");
      test<< "save "<<++n<<endl;
      test.close();
    }
    else if(str=="quit")
    {
    gameOn=false;
    }
  }
ifstream test2("Save.txt");
string str2;
for(int = 0; i<??;i++)// i less than what number?
  {
    test2>>str2;
    cout<<str2<<endl;
  }
test2.close();
Like this:
1
2
3
4
5
6
ifstream test2("Save.txt");
string str2;
while (test2 >> str2) // while extracting next word successfully
{
    cout << str2 << "\n";
}


Also, note the .close()'s in your code are not necessary, because they are called automatically when the stream goes out of scope.

The caveat is that you seem to be implying you expect Save.txt to have more than one number in it. It won't, because you are overwriting the file each time you do lines 9-11.
Last edited on
btw look at this it is supposed to set all my vectors to what p is but it only sets the first one 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
30
31
fstream loadFile("Save.txt", ios::in | ios::out | ios::app);
	int a = 0;
	int l, e, g, c;
	string p, s;
	int z = 0;
	for (int i = 0; i < 4; i++)
	{
		while (getline(loadFile,p))
		{
			getline(loadFile, s);
			z++;
			if (z == 3)
			{
				a = stoi(s);
			}
			if (i + 1 == a&& z==3)
			{
				saveOrder[i] = p;
				loadOrder[i] = p;
				z = 0;
			}
		}
	}
	for (int b = 0; b < 4; b++)
	{
		if (b == 0)
		{
			cout << "0.Back" << endl;
		}
		cout << b + 1 << "." << loadOrder[b] << endl;
	}
I have no idea what is happening there. Try using a debugger and stepping through the code line by line.
Alright thx anyway! good you told me about the close file thing it helped.
Topic archived. No new replies allowed.