reading from file
Aug 26, 2014 at 11:42am UTC
Hey! So I recently started to learn c++. I'm now working with reading from file tasks. I now know how to read all the information from .txt files but im stuck at
making the integers i read from the file to variables. like if the first line in my
failiukas.txt is
2 0 2 and i want to put those numbers to variables x, y, z. how to do it?
1 2 3 4 5 6 7 8 9 10
string line;
ifstream file ("failiukas.txt" );
if (file.is_open())
{
while (getline(file,line))
{
cout << line << '\n' ;
}
file.close();
}
Aug 26, 2014 at 12:23pm UTC
#include <sstream>
7 8 9 10 11
std::istringstream iss (line);
if (iss >> x >> y >> z)
{
//success
}
Last edited on Aug 26, 2014 at 12:24pm UTC
Aug 26, 2014 at 12:27pm UTC
thanks for your answer!
but if my file is:
will it work? as i think u always try to get 3 parameters from file
Last edited on Aug 26, 2014 at 12:27pm UTC
Aug 26, 2014 at 12:28pm UTC
OK, that is not what you originally suggested in your first post. Can each line have any number of values on it?
7 8 9 10 11 12
std::istringstream iss (line);
std::vector<int > v;
while (iss >> x)
{
v.push_back(x);
}
Aug 26, 2014 at 12:32pm UTC
sorry. my bad. yes it can have any number of values.
Aug 26, 2014 at 12:44pm UTC
Did I answer your question then? It's not clear.
Aug 27, 2014 at 8:33am UTC
How all the code should look like?
Topic archived. No new replies allowed.