Question

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std ;

int main()
{
    ifstream infile ;
    infile.open("input.txt") ; 
    string line ; 

    int noOfVar,noOfCubes  ; 

    getline(infile,line) ; 
    istringstream iss(line) ; 
    iss >> noOfVar ; 

    getline(infile,line) ; 
    iss(line) ; 
    iss >> noOfCubes ; 

    cout << noOfCubes ; 
    cout << noOfVar  ; 

    return 0 ; 
}

I have an input file as follows

6 
4

Why isn't the above code working on that . I have declared the iss object once . Can't I use that again ? It is presently showing error in compilation .

Was it helpful?

Solution

You cannot initialize the iss variable again using the constructor method:

iss(line) ; 

You'll need to have another instance of std::istringstream for the second line, or
alternatively you can use the std::istringstream::str() function to set the contents (see here for a working sample).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top