Why do std::istringstream only work here with a constructor?

Viewed 77

The code below compiles and works as expected. On line 11, when I change
std::istringstream iss(temp)
to
std::istringstream iss()
, it stops working. An error occurs on line 18, iss.str(temp):
expression must have class type but it has type "std::istringstream (*)()"

Why would a change to the constructor make a difference? I checked the docs, it shouldn't make a difference, but I must be missing something. Any thoughts?

#include <vector>
#include <iostream>
#include <string>
#include <sstream>

int main() {

    int n, m;
    std::string temp;
    std::vector<int> ranked, player;
    std::istringstream iss();

    // Get the Input

    std::getline(std::cin, temp);
    n = std::stoi(temp);
    std::getline(std::cin, temp);
    iss.str(temp);
    while(!iss.eof()) {
        std::getline(iss, temp, ' ');
        ranked.push_back(std::stoi(temp));
    }

    return 0;
}
2 Answers
std::istringstream iss();

is a declaration of a function iss. Remove the () to declare an object.

Also note that your usage of while(!iss.eof()) is wrong. The loop should be:

while(std::getline(iss, temp, ' ')) {
    ranked.push_back(std::stoi(temp));
}

std::istringstream iss() is the declaration of function with name iss and return value std::istringstream.

Related