I have to take integer input to an integer array. I have to identify the newline also in input. To be more clear, I have an example. The input I am giving is:-
2
int array[42];
int* ptr = array;
for (string line; getline(cin, line); ) {
istringstream stream(line);
stream >> *ptr++;
}
Error checking elided.
The istream extraction operator will automatically skip the blank lines in the input, so the read_ints() function in the below example will return a vector of the whitespace (including the newlines) separated values in the input stream.
#include <vector>
#include <iostream>
using namespace std;
vector<int>
read_ints(istream & is)
{
vector<int> results;
int value;
while ( is >> value )
{
results.push_back(value);
}
return results;
}
int
main(int argc, char * argv[])
{
vector<int> results = read_ints(cin);
for ( vector<int>::const_iterator it = results.begin(); it != results.end(); ++it )
cout << *it << endl;
return 0;
}
The above code stops reading if any of the input cannot be parsed as an int and allows integers to be separated by spaces as well as newlines, so may not exactly match the requirements of the question.
though you mention c++ here is something that i often use to read in an array of doubles from a file
char line[512+1];
unsigned int row = 0 ;
unsigned int col = 0 ;
while( fgets(line, sizeof(line), file) )
{
col = 0 ;
tempChr = strtok(line, delimters);
// ignore blank lines and new lines
if ( tempChr[0] == '\n' )
{
continue ;
}
tempDbl = atof(tempChr);
data[row*numCols+col] = tempDbl ;
for(col = 1 ; col < numCols ; ++col)
{
tempDbl = atof(strtok(NULL, delimters));
data[row*numCols+col] = tempDbl;
}
row = row + 1;
if( row == numRows )
{
break ;
}
}
You can use std::getline from <string> to read whole lines and use a std::stringstream, from <sstream> to parse the lines.