The stringstream >> operator does not work as a function, but it works as an instance?

I am writing simple code that will extract a bunch of name, int pairs from a file. I am modifying existing code that just uses:

string chrom;
unsigned int size;
while ( cin >> chrom >> size ) {
    //  save values
}

But I want to use another (similar) input file that has the same first two columns, but is followed by other data (which will be ignored). Therefore, I write:

string chrom;
unsigned int size;
string line;
while ( getline(cin, line) ) {
    if( stringstream(line) >> chrom >> size ) {
        // save values
    }
}

But this does not compile, giving a typical obscene std lib spew pattern:

 error: no match for "operator>>" in "std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >(((const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)((const std::basic_string<char, std::char_traits<char>, std::allocator<char> >*)(& line))), std::operator|(_S_out, _S_in)) >> chrom"
istream:131: note: candidates are: std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>& (*)(std::basic_istream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
[...another dozen lines...]

Right the string is not std :: string, but some variation of std :: basic_string, etc. However, an instance of stringstream is explicitly created.

string chrom;
unsigned int size;
string line;
while ( getline(genome, line) ) {
    stringstream ss(line);
    if ( ss >> chrom >> size ) {
       // save values
    }
    // Discard remainder of line
}

Why? What is wrong with the first case? The basic_io example in the always useful cplusplus.com works, why does my code not work?

: : stringstream , int :

unsigned int chrom;  // works as int...
unsigned int size;
string line;
while ( getline(cin, line) ) {
    if( stringstream(line) >> chrom >> size ) {
        // save values
    }
}
+3
4

- " " ( → ), . http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/.

  • stringstream (); -
  • stringstream ss (); - .

"chrom" - int, → , -. .

"chrom" , → istream& operator>> (istream& is, char* str), , . , , ​​ ++. , istream& operator>> (const istream& is, char* str). , . () , , , error: no match for function...

+2

C ++ , lvalue, .. .

- .

+2

, extrace " → " :

  • .
  • .

, , . , , .

+2

, , std::string. , , int, stringstream (line) .

stringstream std::string - → . , lvalue.

, ... , , .

+1

Source: https://habr.com/ru/post/1724337/


All Articles