C ++: reading in arguments with a single istringstream object

int i1;
std::istringstream z(argv[1]);
z >> i1;
cout << i1;
z.str(argv[2]);
int i2;
z >> i2;
cout << i2;

This is my code. My first argument is 123, and the second argument is 12. I expect the result to be 12312. Instead, I see 1234196880. Why? I thought that with the str method, could I reset pass the stream to the second argument and read it?

+4
source share
2 answers

, istringstream, .

, :

template<typename TargetType>
TargetType convert(const std::string& value) {
    TargetType converted;
    std::istringstream stream(value);
    stream >> converted;
    return converted;
}

, , reset :

int i1 = convert<int>(argv[1]);
int i2 = convert<int>(argv[2]);

: ++ 11, std:: stoi

0

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


All Articles