Reading data in from file?

Hi!

I'd like to read in a simple row of integers from a .txt file and sort the numbers into an int array. The numbers are separated by space characters, like this:


1 2 3 4 5 6 7 8 9 10


Now, there's where I'm a bit stuck: I'm not sure how to cut up the data by the space characters and put them to the [i]th element of the int array. I was thinking about reading in the data into a string and cut them up by finding the space characters, as I have numbers above 9, with two digits - and going through the string with a for loop caused my numbers to get cut up by only signle digits.

Could you help me out, please?
Last edited on
C or C++?

C++ :)
As C++, consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>

int main()
{
	std::ifstream ifs("nums.txt");

	if (!ifs)
		return (std::cout << "Cannot open file\n"), 1;

	std::vector<int> vi;

	for (int i; ifs >> i; vi.push_back(i));

	std::sort(vi.begin(), vi.end());
	std::copy(vi.begin(), vi.end(), std::ostream_iterator<int>(std::cout, " "));
	std::cout << '\n';
}



1 2 3 4 5 6 7 8 9 10

It worked!! Thank you very, very much :D
Topic archived. No new replies allowed.