Grav Grav - 1 year ago 80
C++ Question

How to iterate over a line in a file?

I have a file that contains integers organized into rows and separated by whitespace. Both the number and length of the rows are unknown.

I'm currently iterating over the file line-by-line, and I'm trying to iterate over each line character-by-character but I'm having some trouble. I'm currently storing the contents of each line into a string, but I suspect that's not the best way, and I'm hoping someone can point me in the right direction.

Here's my current code which simply prints each line in the file:

std::string filename = "values.txt";
std::ifstream file(filename.c_str());
std::string line;

while (std::getline(file, line))
std::cout << line << std::endl;

I'm coming from python, which could easily implement this, like so:

for line in file:
for char in line:
print char

However, not knowing the length/number of rows for the for loops is throwing me off as I'm fairly new to c++. I'd also like to read the characters as ints instead of a string, but I haven't been able to figure that one out either. What would be the most correct way to implement this in c++?

Any help is greatly appreciated.

Answer Source

You're almost there; you can use formatted stream extraction to read integers, using a string stream to represent each line:

#include <fstream>
#include <sstream>
#include <string>

// ...

for (std::string line; std::getline(infile, line); )
    std::istringstream iss(line);
    for (int n; iss >> n; )
        std::cout << "Have number: " << n << "\n";
    std::cout << "End of line\n";

Error checking can be added by checking whether the entire string stream has been consumed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download