error: expected initializer before

I just need help finishing this. We have to open and close the file.
There are errors on lines: 9, 10, 11, and 14. Please help.

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
 #include <iostream>
 #include <string>
 #include <fstream>
  using namespace std;
  int main ()
   {
   cout << "Enter the file name " << endl;
   ifstream randomtext ;
   string randomtext.c_str() ;
  cin >> randomtext;
  randomtext.open(randomtext.c_str());
  if (randomtext)
  {
  while (randomtext >> number)
  {
  cout << number << endl;
  }
  randomtext.close();
  }
  else
  {
  cout << "There is an error opening the file." << endl;
  }
  return 0;
  }
Last edited on
Please remove the line numbers - the forum puts them for you. It is difficult to copy and paste to run your code.

You can't give two variables the same name (lines 8, 9, 10, 11).
closed account (2LzbRXSz)
Along with those errors, number isn't defined.
Sorry I'm new to this. We were supposed to save a random list of numbers and open it with this program. I can't name those things the same? Then what should I name them? I thought they were supposed to be the same as the file I'm opening.
The names of your variables has absolutely nothing to do with the names of the files you are working with. You can, however, store the name of a file inside of a string variable.
Well what exactly are you saying? Where should the actual file be named? What can be named something else?
On line 8, you create a variable named randomtext. This variable just so happens to be an input file stream. Then on the very next line you (try to) create another variable with the same name. You probably wanted to do this instead:
8
9
10
11
  string filename;
  cin >> filename;
  ifstream in (filename.c_str());
  if(in)
If you are using C++11, you don't need .c_str().
Last edited on
Thank you. I kept thinking filename meant that I had to put in the name of the file. But I still need to get the file in the file somehow. I need to use it for math and I need to open and close it. Randomtext is not declared. How would I declare a file?
Compare your original line 12 to my suggested line 11 and I think your confusion will vanish.
Last edited on
Topic archived. No new replies allowed.