|
Prev: Waiting on a pipe
Next: Function not recognizing
From: Matt Osborn on 12 May 2008 11:01 Is my usage of std::setw incorrect? The following code results in a single character ('t') placed into the string text. If I replace 'is >> std::setw (1) >> colon' with is.get (), the code works as expected. I'm testing this with VC++ 2005. #include <iostream> #include <sstream> #include <iomanip> int main (int, char*) { std::istringstream is ("123:456 text"); int prefix = 0; if (is >> prefix) { char colon = 0; if (is >> std::setw (1) >> colon) { int suffix = 0; if (is >> suffix) { std::string text; if (is >> text) { std::cout << text; } } } } }
From: Alex Blekhman on 12 May 2008 11:43 "Matt Osborn" wrote: > Is my usage of std::setw incorrect? The following code results > in a single character ('t') placed into the string text. If I > replace 'is >> std::setw (1) >> colon' with is.get (), the code > works as expected. > > I'm testing this with VC++ 2005. > > #include <iostream> > #include <sstream> > #include <iomanip> > > int main (int, char*) > { > std::istringstream is ("123:456 text"); > int prefix = 0; > if (is >> prefix) > { > char colon = 0; > if (is >> std::setw (1) >> colon) > { > int suffix = 0; > if (is >> suffix) > { > std::string text; > if (is >> text) > { > std::cout << text; > } > } > } > } > } Aparently the width value is retained by `std::ios_base' object and used afterwards for strings. I'm not sure why subsequent integer extraction is not influenced by this setting. In any case you can use the following workarounds: 1. Do not use `std::setw' at all. When you extract just one character there is no sense in setting the width to 1. Only one character will be extracted anyway. 2. Reset the width value to default (0) before extracting strings: is >> std::setw (0) >> text This way you will obtain full string until next delimiter. 3. Use sscanf/sscanf_s. This approach is not as nice and object oriented as C++ streams, however is much easier to use. I personally find C++ streams painful when you need to do formatted input/output. HTH Alex
|
Pages: 1 Prev: Waiting on a pipe Next: Function not recognizing |