Reputation:
I am trying to read the following contents:
rima doha 44881304 20 30 10 10 20 10102 10102
andrew ny 123456 12 12 13 14 15 01020 03040
and store them in separate arrays, edit them, then store again into the same file.
Here is my attempted code:
ifstream infile;
infile.open("D:\\customers.txt");
string names[100];
string addresses[100];
int tn[100];
int numCalls[100];
int trunkCalls[100];
int numMobCalls[100];
int isdnNum[100];
int dueD[100];
int paymentD[100];
int numOfPpl = 0;
int numOfPpl = 0;
for(int i=0; i<100; i++){
infile >> names[i] >> addresses[i]>>tn[i]>>numCalls[i]>>trunkCalls[i]>> numMobCalls[i]>> isdnNum[i]>>dueD[i]>>paymentD[i];
numOfPpl++;
}
//Code where some values were edited
ofstream outfile("D:\\customers.txt");
for(int i=0; i<numOfPpl; i++)
{
outfile<<names[i] << "\t" <<addresses[i] << "\t" <<tn[i]<<"\t" <<numCalls[i]<<"\t"
<<trunkCalls[i]<<"\t"<<numMobCalls[i]<<"\t"<<numMobCalls[i]<<"\t"<<isdnNum[i]<<"\t"<<dueD[i]<<"\t"<<paymentD[i]<<endl;
}
outfile.close();
infile.close();
Issue is that the first two lines are stored correctly, but then there are random values in the file. How do I fix this?
Upvotes: 0
Views: 944
Reputation: 124
There's a couple things wrong with your code.
First, you declare numOfPpl twice. Get rid of the 2nd count.
Secondly, you have 9 input categories (names, addresses, etc.), but your text file has 10 per line. This will throw the entire program off.
The third issue is are you going to have exactly 100 lines in the customers.txt? If not, you should utilize a command to peek to the next line to make sure if there's another line below. Using a while or do/while loop would probably be better if there aren't 100 lines in your text file. Something like
while(infile){
// retrieve your data
infile.peek();
}
or utilizing the for loop
for(int i = 0; infile; i++){
// retrieve your data
infile.peek();
}
would probably be a better loop. Again, if you're not going to have 100 lines, the for loop will give you the null output because there isn't any data being put into the array elements. I believe that should correct your issues.
Another thing you should watch out for is having an extra space at the end of a line. That'll throw your program output off as well.
Upvotes: 1