C++ - Repeatedly Using Istringstream

C++ - repeatedly using istringstream

After setting the row into the istringstream...

separate.str(row);

... reset it by calling

separate.clear();

This clears any iostate flags that are set in the previous iteration or by setting the string.
http://www.cplusplus.com/reference/iostream/ios/clear/

C++: read in arguments with one istringstream object

When you do

z.str(argv[2]);

the function internally calls the str member of its internal string buffer object (http://www.cplusplus.com/reference/sstream/stringbuf/str/) and just sets the contents of the string buffer. You need to rewind the pointer in order to use the newly set buffer (http://en.cppreference.com/w/cpp/io/basic_istream/seekg)

Using stringstream object multiple times

stringstream is a subclass of istream, so stream >> n (std::istream::operator>>) returns a reference to istream

stream can be converted to bool (std::ios::operator bool): it converts to false when it no longer has any data (reached end-of-file)

You have finished reading stream in your first loop - it no longer has any data.

If stream object is getting emptied at the end of the first while loop is there any workaround to restore it back to initial condition?

You need to store values on your own and then reuse them - copying streams is not allowed (it doesn't make sense for them really) - Why copying stringstream is not allowed?

Issues in using istringstream

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).

Running function with ifstream and stringstream multiple times

My suggestion:

std::string Qual(double *a)
{
std::string line;
char Qualities[] = {'1', '2', '3', '4' ,'5', '6', '7','8','\0'};
std::string Read_qual;

std::srand(std::time(nullptr));
std::random_device rd;
std::default_random_engine gen(rd());
std::discrete_distribution<> d({a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7]);
Read_qual += Qualities[d(gen)];
return Read_qual;
}

and the main()

 int main()
{
std::ifstream infile("Freq.txt");
double alldata[150][8];
for (int i=0, i<150; i++)
for (int j=0; j<8; j++) infile >> alldata[i][j];
infile.close();

for (int idx = 0; idx < 2000; idx++)
{
for (int row = 0; row < 150; row++)
std::cout << Qual(alldata[row]) << std::endl;
}
return 0;
}


Related Topics



Leave a reply



Submit