user3671292
user3671292

Reputation: 83

read one line with integers c++

i am making an algorithm and i need to read a whole line full of integers in c++
my input file is :
//////
5
6 3 4 2 5
//////
i want to read the second line and take the integers one by one
I don't want to take the integers to a variable because i have a memory limit(64 mb of ram)
i want to take the integers directly from the file
is there any way to do it in c++(not c)

i have tried this

fstream file;
file.open("file.txt");
int a;
file >> a;

But with this i can make it only read the "5" and if i use something like "getline();" i can't get each integer as i want
Thanks

Upvotes: 1

Views: 3692

Answers (1)

outlyer
outlyer

Reputation: 3943

You don't have to save each integer in its own variable, simply re-use the same one

fstream file("file.txt");
int a;
while (file >> a) {
   // Do your stuff with "a"
}

To skip the first number (as per the question below), one easy way is to read and discard the integer once:

fstream file("file.txt");
int a;
file >> a; // Do nothing with a → Discard the first value
while (file >> a) {
   // Do your stuff with "a"
}

Upvotes: 1

Related Questions