Hello everybody,
I am beginner and I just come to C++
I want to read the file, line by line, and line as array, like this:
my file:
1 2
6
1 2 4 5 2 1
And I want to get: n=6 and my array, A[] = {1,2,4,5,2,1}
First line to N variable and second line to A array.
I did this, but it didn't make sense
Please help, thank you!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
ifstream F;
string line;
F.open("SN.INP");
if (F.is_open())
{
while(getline(F,line))
{
cout<<line<<'\n';
}
F.close();
}
else
cout<<"file couldn't be opened";
If you want to parse the contents of a string, you could use a stringstream object:
1 2 3 4 5 6 7 8 9 10
// Get the line containing the number of elements & put it into a string
getline(F,line);
// Put the contents of the string into a stringsteam object for parsing
std::stringstream ssLine;
ssLine.str(line);
// Grab a single int from the stringstream - no error-checking here!!!
int numElems;
ssLine >> numElems;
// Initialise an array for storing numElems ints
int * elements = newint[numElems];
You need to #include <sstream> and then do something similar for the next line, where you want to extract the requisite number of ints from the stringstream object & populate your array with them.