Reputation: 1075
I have a file with random data for accounts. The data in the file:
5
2871 2.19 8
1234 95.04 23
3341 0.00 10
3221 -1.08 21
7462 404.14 4
3425 4784.00 200
3701 99.50
JUNK SHOULD NEVER GET HERE
3333
The first number 5 will always be the number of accounts that need to be processed. I want to be able to read that number and set it as the number of accounts.
So my question is how can I read the file and read line by line and set the first number to the number of accounts that need to be processed.
Code so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
double NumberOfAccounts;
ifstream File("test.dat");
string line;
if(File)
{
while(getline(File,line))
{
NumberOfAccounts=line[0];
}
File.close();
}
cout<<NumberOfAccounts;
system("pause");
return 0;
}
Right now it just prints out 51.
Any tips/help would be appreciated.
Upvotes: 0
Views: 14402
Reputation: 20330
NumberOfAccpounts is double, you are assigning the first character of line... I assume you menat the first line in the file.
My C++ is crap so
pseudocode
if(File)
{
if getLine(File, line)
{
NumberOfAccounts =atof(line);
}
File.close();
}
cout<<NumberOfAccounts;
system("pause");
return 0;
atof is one way to convert a string to a double. You don't need to read the entire file to get the first line.
Upvotes: 1
Reputation: 9642
Two things. One, you're getting stuck in a while loop (while there's a line left, read it in and re-assign the number of accounts) until the end of the file. Secondly, ASCII numbers do not correspond to actual numbers, so the character "0" is actually the number 48. You're getting 51 as the program reads the last line, finds the "3" character, assigns that to an integer (which is now 51), then outputs it.
Upvotes: 2