Hi, I want to read a bunch of two-digit numbers from a file and put them into an array, without any specifications about how many I'm supposed to read. Is there any way to read them so the reading stops at the end of the file?
std::vector<int> v;
std::ifstream in;
in.open("digits.txt");
if(!in.fail())
{
while(!in.eof())
{
int num;
std::string line;
...//read line and convert into int
v.push_back(num);
}
}
in.close();
Thanks for the reply but I have no idea what that is... I think I should have mentioned that the only way I know to read from files looks like this (I'm a high school student with no extra experience in programming):
int n;
ifstream f("data.in");
ofstream g("data.out");
f>>n;
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
int main()
{
std::vector<int> v;// create vector that can hold int's
std::ifstream in;
in.open("digits.txt");//open digits.txt
if(!in.fail())//test if opened
{
while(!in.eof())//while not end of file
{
int num;
std::string line;
in >> line;//read into string
num = atoi(line.c_str());//konvert string of chars into int
v.push_back(num);//add value into vector
}
}
in.close();//close file after done
//print contet of vector/array
for(unsignedint i = 0; i < v.size(); ++i)
{
std::cout << "v[" << i << "] = " << v[i] << std::endl;
}
std::cout << "Press enter to exit...";
std::cin.get();
return 0;
}
I think I get it now...so the idea is to read them as characters, see if they're different from the end-of-file character, and then convert to numbers? Any idea on how the end-of-file character is noted if I want to write line 13 like
I didn't understood you well. Do you want to stop reading if 'x' is some arbitary value (that you've choosen)?
Say:
digits.txt
22
33
4
78
666
12
47
let say you want to stop where x is 666
then:
1 2 3 4 5 6 7 8 9 10 11 12 13
if(!in.fail())//test if opened
{
while(!in.eof())//read until end of file
{
int num;
std::string line;
in >> line;//read into string
num = atoi(line.c_str());//konvert string of chars into int
if(num == 666)//if it is 666
break;//quit reading
v.push_back(num);//add value into vector
}
}