By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,291 Members | 3,120 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,291 IT Pros & Developers. It's quick & easy.

How to read from a text file?

P: 19
Hello,

I am supposed to read from a text file a series of numbers and then store them in a struct array.

Here's my code:

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.     ifstream In;
  4.     string folder, filename, name2, line;
  5.     int i = 0;
  6.  
  7.     cout << endl << "Enter the name of the folder" << endl;
  8.      cout << "Follow the format: c:/your_folder_name/ :";
  9.      cin >> folder;
  10.      cout << "Enter the name of the file: " ;
  11.      cin >> filename;
  12.  
  13.      name2 = folder + filename + ".txt";
  14.      In.open(name2.c_str());
  15.  
  16.  
  17.    do
  18.    { 
  19.  
  20.          In >> array[i].var1 >> array[i].var2 >> array[i].var3;
  21.          i++;
  22.          cout << i << " " << array[i].id;
  23.  
  24.    } while (getline(In, line));
  25.  
  26.  
  27.    In.close();
  28.    system ("PAUSE");   
  29.    return 0;
  30. }
And this is the input file:

1 1230 1420
2 1150 1115
3 1520 1314
4 1345 1234
5 1130 1230
6 1120 0430
7 1720 1810
8 1122 1125
9 1123 1130
10 1125 1132
23 1145 1122


The code is not reading the file at all. Also the variable 'i' being used is not incrementing either. Could anyone please help?
Mar 10 '11 #1
Share this Question
Share on Google+
2 Replies


Banfa
Expert Mod 5K+
P: 8,916
What output do you get?
How is array declared?

You output array[i].id and that member is never assigned to.
Mar 10 '11 #2

P: 19
Sorry, I should have mentioned it earlier, I declared it as a global array. Thanks for replying, my code is working now, I used vectors to declare an array and get the file data instead of the method above.
Mar 11 '11 #3

Post your reply

Sign in to post your reply or Sign up for a free account.