Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: read in arguments with one istringstream object

Tags:

c++

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

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

like image 322
user3182532 Avatar asked Apr 23 '14 13:04

user3182532


Video Answer


2 Answers

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)

like image 99
Marco A. Avatar answered Oct 20 '22 10:10

Marco A.


I'll assume you're only using istringstream in order to easily convert strings to integers.

If so, I'd recommend writing a helper function:

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

That way, your code becomes more readable, and you avoid having to reset the stream for each conversion:

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

Edit: If your compiler supports C++ 11, you could also simply use std::stoi

like image 20
lethal-guitar Avatar answered Oct 20 '22 11:10

lethal-guitar