ifsteam for loop not working

I'm trying to make a file named test.txt that looks like:
line1
line2
line3

say

the name is (line1)
the age is (line2)
the snack is(line3)



The ifstream reads the three lines but does not add "the ___ is:" to it.

No matter what input I put into cin, it reads test.txt too :(

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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {

  int i;
  string file;
  string line;
  cout << "What is the name of the file?" << endl;
  cin >> file;
ifstream giveit(file);

  if( ! giveit.good() ) 
  {
    cerr << "Error" <<endl;
  } else if (giveit.good())
 {
    for(i=0;i<3;i++)
   {
      if (getline(giveit,line))
      {
        if(i==0)
        {
          cout<<"The name is: "<< line <<endl;
        } 
        else if(i==1)
        {
          cout<<"The age is: "<< line <<endl;
        } else if(i==2)
        {
          cout<<"The snack is: "<< line <<endl;
        }
      }

    }
  }
  giveit.close();
  return 0;
}

Last edited on
I compiled your code and was able to get the program to read the lines from a file, then print the "The name is: Tom" messages on screen.

It sounds like you want to save the output to a file. If so, you can use ofstream to open a new file and save the contents there: http://www.cplusplus.com/reference/fstream/ofstream/ofstream/
Thank you!
Last edited on
Topic archived. No new replies allowed.