|
|||||||
![]() |
|
|
LinkBack | Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
#1 |
|
Member (5 bit)
Join Date: Jul 2004
Posts: 24
|
C++ Problem
I'm writing a program to read data from a file and then store the results in variables for later calculations, and save the iresults to an outfile. The program reads in the name of a state, that states electoral votes, and the number of votes each candidate got in the 2000 election. An examlpe of the data:
State Elec Vote Gore Bush Nader Buchanan Alabama 9 695602 944409 18349 6364 Alaska 3 79004 167398 28747 5192 Opening and reading from a file and saving and closing the data isn't a problem, but I'm having a hard time setting up the loop to read in all the data. I know the .getline function is what I should more than likely use, but i'm having problems with the syntax. Also, should a seperate loop be setup to read the first line so it doesn't store junk in the variables? Any help would greatly be welcome. Thanks. |
|
|
|
|
|
#2 | ||
|
Member (9 bit)
|
Dont use getline..Use a while loop for the inputs into a 2dim array.
Code:
#include fstream.h // put carrots on these *
#include iostream.h // put carrots on these *
#include apstring.h // put carrots on these *
void main(){
long int states[50][5];
apstring state_name[50];
int x = 0;
ifstream infile;
infile.open("c:\states.txt");
while ( !infile.fail() && x < 50 )
{
infile >> state_name[x]; // state name
infile >> states[x][0]; // elec votes
infile >> states[x][1]; // gore
infile >> states[x][2]; // bush
infile >> states[x][3]; // nader
infile >> states[x][4]; // buchchanan
x++;
}
x = 0;
while (x <= 49)
{
cout << state_name[x] << " ";
cout << states[x][0] << " ";
cout << states[x][1] << " ";
cout << states[x][2] << " ";
cout << states[x][3] << " ";
cout << states[x][4] << " " << endl;
++x;
}
}
edit: To skip the first line of strings, just do 7 CINs.. Dave
__________________
Last edited by daveyp225; 10-31-2004 at 01:04 PM. |
||
|
|
|
![]() |
| Bookmarks |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|