I have a difficult assignment and one of the parts requires me to take a .txt file full of numbers (1 number per line) and put it into an int array. With the following code below, my problem is the conversion from string to int becomes 0. I have tried stringstreams and a variety of other approaches, but none of them work. I would appreciate help where ever I can get it :)
while(!fin.eof()) {
getline(fin, line);
if (!line.empty() && isdigit(line[0]))
lineNumbers++;
}
//create & fill array
fin.clear();
fin.seekg(0, ios::beg);
int* arr = newint[lineNumbers];
cout << "Input File contains:" << endl;
for(int i = 0; !fin.eof(); i++) {
getline(fin, line);
if (!line.empty() && isdigit(line[0]))
{
arr[i] = atoi(line.c_str());
cout << arr[i] << endl; // to check the array content
}
}
Simply check if line is empty or not. If line is empty then don't count it.
Furthermore, you should check if line is a number or not by checking its first char. If its first char is a digit char ('0' - '9') then count it.
Another way around is using >> operator... However this technique will stop at an invalid line (not an empty line) such as "7a"
1 2 3 4 5 6 7 8 9 10 11 12 13
int temp;
while (fin >> temp)
++lineNumbers;
// allocate arr and rewind fin
//....
for (int i = 0; fin >> temp; ++i)
{
arr[i] = temp;
cout << arr[i] << endl;
}