How can I read from a txt file?

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Oct 2004
Posts: 6
Reputation: nicoletonyf is an unknown quantity at this point 
Solved Threads: 0
nicoletonyf nicoletonyf is offline Offline
Newbie Poster

How can I read from a txt file?

 
0
  #1
Oct 5th, 2004
Hello there, My program is supposed to read data from a txt file, and put this data in a 2 dimension array. All I have is the last line of data in my text file. My teacher said that I have to update the array in my loop. I have no idea how to do it. Can someone help me? Nicole
example of txt file
1 2 3
4 5 6
...
int main()
{
const int TYPE = 3;
const int COUNTRY = 50;

int result[COUNTRY][TYPE] = {0};
int totalPoint[COUNTRY] = {0};
int numGold,numSilver,numBronze;
int cntCountry = 0;
int totalMedal = 0;


while(!cin.eof() )
{

cin >> numGold >> numSilver >> numBronze;

if(numGold > 0 || numSilver > 0 || numBronze > 0)
{
++cntCountry;
}
}


for ( int i = 0; i < cntCountry; ++i )
{
result[i][0] = numGold;
result[i][1] = numSilver;
result[i][2] = numBronze;


}
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 7,580
Reputation: Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute 
Solved Threads: 709
Team Colleague
Narue's Avatar
Narue Narue is offline Offline
Code Goddess

Re: How can I read from a txt file?

 
0
  #2
Oct 5th, 2004
> while(!cin.eof() )
This is a bad idea and will probably result in you processing the last line of the file twice. A better method is to use your input as the condition:
  1. while ( cin >> numGold >> numSilver >> numBronze )
Without knowing the format of your file, I have to assume that your teacher meant this change:
  1. result[i][0] += numGold;
  2. result[i][1] += numSilver;
  3. result[i][2] += numBronze;
At the end of the file, the array has a total of everything rather than the values of the last line.
I'm here to prove you wrong.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC