Input/Output with Files Trouble

I want to read from a file called test.txt that has the following terms
1945
egg
vegetable

I have both a file with above called test.txt and the code below in the same file. I want the console output it should be:
The age is 1945
The name is egg
The snack is vegetable
When I run the program it gives me http://pastebin.com/5PnWrLHY



What do I need to change in my code to get this message to work?


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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
  int i;
  string file;
  cout << "What is the name of the file?" << endl;
  cin >> file;
  ifstream giveit(file);

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

    }
  }
  giveit.close();
  return 0;
}
Last edited on
> ifstream giveit(file);
> no known conversion for argument 1 from ‘std::string’ to ‘const char*’
As you can see here http://www.cplusplus.com/reference/fstream/ifstream/open/ you need c++11 to use a string to open a file. (-std=c++11 flag for gcc)

As an alternative, you may use the other constructor (the one that expects an const char* ifstream giveit(file.c_str());


> error: expected primary-expression before ‘<<’ token
file << <<endl; you've got too many <<, it should be file << endl;


By the way, don't change the meaning of your variables. `file' was supposed to hold the file name, but later you use it to capture the age, name and snack

Edit: consider also to update your compiler.
Last edited on
Line 24: You have two <<'s together before endl;

ne555 beat me to it.
Last edited on
fixing it, it says,


lab08.cpp:11:22: error: expected initializer before ‘giveit’
const char* ifstream giveit(file.c_str());
^
lab08.cpp:14:19: error: ‘giveit’ was not declared in this scope
if (getline(giveit,line))
^
lab08.cpp:14:26: error: ‘line’ was not declared in this scope
if (getline(giveit,line))
^
lab08.cpp:30:3: error: ‘giveit’ was not declared in this scope
giveit.close();
^

How do I add an initializer before giveit and declare it and the new variable?
Topic archived. No new replies allowed.