Search code examples
c++getlinefileinputstream

isstringstream reading from file c++


I am trying to read a file of numbers.

Using my code, I read the first number only of each row. getline() gets the line but isstringstream reads only 1 number from the line neglecting the rest. I need to read each number and insert it in my vector

The file example is:

118 115 115 116 116 116 118 117 115 114 114 115 117 118 117 114 114 116 117 
116 117 117 117 116 115 115 115 115 116 118 118 117 116 114 112 112 112 114 
115 ... so on

int main()
{
vector<unsigned char>gray;
int lines=2;

    for (int i = 0; i < lines; i++)

    {
        string line4;
        getline(infile, line4);
        istringstream iss4(line4);
        int g;
        iss4 >> g;

        gray.push_back((unsigned char)g);
    }
return 0;
}

Solution

  • Changing your code a bit:

    #include <cstdint> // For uint8_t
    
    int main()
    {
        vector<uint8_t>gray;
        unsigned int line_number = 0U;
        std::string text;
        while (getline(infile, text))
        {
            istringstream iss4(text);
            uint8_t value;
            while (iss4 >> value)
            {
                gray.push_back(value);
            }
        }
    return 0;
    }  
    

    Notes:

    1. The istringstream can be treated like a file, when extracting more than one value.
    2. The uint8_t type guarantees 8-bit unsigned integer.