string from .txt file to int array

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 :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <fstream>
#include <cassert>
#include <string>
#include <sstream>
#include <vector>
#include <stdlib.h>
using namespace std;

int main(int argc, char* argv[]) {
	string input = argv[1];
	string output = argv[2];
	int lineNumbers = 0;
	
	//open input & output files
	ifstream fin;
	fin.open(input.c_str());
	assert(fin.is_open());
	
	ofstream fout;
	fout.open(output.c_str());
	assert(fout.is_open());
	
	//calculate # of lines
	string line;
	while(!fin.eof()) {
		getline(fin, line);
		lineNumbers++;
	}
	//create & fill array
	fin.clear();
	fin.seekg(0, ios::beg);
	int* arr = new int[lineNumbers];
	cout << "Input File contains:" << endl;
	for(int i = 0; !fin.eof(); i++)	{
		getline(fin, line);
		arr[i] = atoi(line.c_str());
		cout << arr[i] << endl;	// to check the array content
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
	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 = new int[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;
}
Last edited on
I have made the modifications you suggested and the output is now nothing at all.

I would also like to mention the input file, without a doubt, will have this format:

number
number
number

for example:
2
7
12

There will be no spaces or other characters.
Last edited on
Topic archived. No new replies allowed.