I have a text file called number.txt and its containers are some numbers separated with a new line and spaces:
number.txt
10 20
44 56 7 8
I have a basic algorithm to get all of them together but i want to get the two first numbers as two different variables e.g(n = 10 and w = 20 for this example) and i want to get the remaining into the array starting from 0 (I mean that i want list[0] = 44 for this example)
#include<cmath>
#include<string>
#include<iostream>
#include<fstream>
usingnamespace std;
int main ()
{
int n; // number read from file
int list[5];
ifstream inFile; // the input file
inFile.open("number.txt");
// Exit if there was an error
// opening the file
if (!inFile)
{
cout << "Error opening input" << endl;
return -1;
}
// Loop through the input file
while ( !inFile.eof() )
{
//inFile>> n;
n=0; // To refer each block of the array
while ( !inFile.eof() )
{
inFile>> list[n]; //assigning the content of the block of the array
n++; //increasing each time by 1
}
}
// close the input file
inFile.close();
int no = 0;
//Display array numbers
while(no<4)
{
cout<<list[no] << " "; // the number i want to output
no++;
}
// system("pause");
return 0;
}
You read an integer into a variable n.
You read an integer into a variable w.
while (you successfully read an integer into variable x)
{ append x to list }