1

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.

Grav
  • 461
  • 6
  • 18
  • Have you checked [here](http://stackoverflow.com/questions/20710172/looping-through-every-character-in-user-input) and [here](http://stackoverflow.com/questions/9438209/for-every-character-in-string)? – TigerhawkT3 Sep 24 '16 at 22:58
  • I don't get what's your problem actually? Reading lines with `std::getline()` as you show it is perfect. – πάντα ῥεῖ Sep 24 '16 at 22:58
  • You can use [this answer](http://stackoverflow.com/questions/236129/split-a-string-in-c/236803#236803) to a previous post that will tell you how you can split the string you get from each line, then you can operate on the individual strings (convert them to ints, doubles, etc...) – Jvinniec Sep 24 '16 at 22:58
  • Are you familiar with [stringstream](http://www.cplusplus.com/reference/sstream/stringstream/stringstream/)? – Beta Sep 24 '16 at 22:59
  • [this answer](http://stackoverflow.com/questions/2287121/how-to-read-groups-of-integers-from-a-file-line-by-line-in-c) may get you pretty close. From there, you could pretty easily store lines of data into sets of vectors if you need. Lots of examples on stackoverflow. – lakeweb Sep 24 '16 at 23:04

1 Answers1

2

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084