Reputation: 21
I've been wracking my brain trying to figure this out. I am trying to read a line of integers from a file, they will look something like this:
20 4 19 1 45 32
34 23 5 2 7
All numbers are between 1 and 100 and are separated by a space. I would like to store each integer as an element in an array which will be fed into a merge sort, but I do not know how to take each integer from the string. Any help is appreciated. Thanks!
Upvotes: 1
Views: 424
Reputation: 1782
There are two steps. Some of these other answers are assuming you want to read the whole file into a single vector; I'm assuming you want each separate line to be in its own vector. This is not the complete code, but it should give you the right idea.
First, you need to read through the file line-by-line. For each line, read it into a std::string using std::getline, where the file itself is opened using an ifstream. Something like this:
ifstream in_file( "myfile.txt" );
string s;
while( in_file.good() )
{
getline( in_file, s );
if( !in_file.fail() )
{
// See below for processing each line...
}
}
Given that you have read in a line, you should load it into a std::stringstream, then read the integers from that stringstream.
vector< int > result;
stringstream ss( s );
while( ss.good() )
{
int x;
ss >> x;
if( !ss.fail() )
result.push_back( x );
}
This part goes in the inner loop above. At the end of this block of code, the result
vector will contain all the integers from the line stored in s
.
By the way, there are some nice tricks with stream iterators (see the other answers) that can make this code a bit more brief. However, I like this style--it's fairly easy to adapt to more complex line formatting later on, and it's easier to add error checking.
Upvotes: 0
Reputation: 490228
First of all, you don't really want an array--you want a vector
.
Second, using a vector
and a couple of istream_iterator
s, you can read the data directly from the file into the array, with no intervening string (well, there could be one, but if so it's hidden in library code, not anything you write).
// Open the file:
std::ifstream in("yourfile.txt");
// Read the space-separated numbers into the vector:
std::vector<int> { std::istream_iterator<int>(in),
std::istream_iterator<int>() };
Note that this does assume you want to read all the data from the file into the single vector of int
s. If (for example) you only wanted to read the first line of data, and leave the remainder untouched (for reading by some other code, for example) you'd typically end up reading the first line into a string, then creating a stringstream
of that data, and using code like above to read the data from the stringstream
.
Upvotes: 1
Reputation: 172934
You can read them into a vector:
std::ifstream dataFile("ints.dat");
std::istream_iterator<int> dataBegin(dataFile);
std::istream_iterator<int> dataEnd;
std::vector<int> data(dataBegin, dataEnd);
Upvotes: 1