开发者

C++ Overloading the >> operator

I need to overload the stream extraction operator. I need to do this by allowing a user to input a string of characters at a prompt开发者_Go百科, say "iamastring", and then the operator would extract each character from the string and test whether or not it is whitespace and if it is not whitespace store it in a character array which is then passed to an object.

@Chip et al. For example output I am not expecting it to output anything to the screen. Instead after a user types in a string and hits enter the user should be prompted again to enter a new menu selection. As it stands right now the user inputs a string hits enter and then a "bad read error" is displayed and the prompt comes back up awaiting new input.


It's quite funny - your name is like mine, but reversed :)

How about:

char buffer[buffSize+1]; // no need for dynamic allocation here
unsigned i = 0;
while(std::cin && !std::isspace(std::cin.peek()) && i < buffSize)
  buffer[i++] = std::cin.get();
buffer[i] = '\0'; // null termination can be important.
// i now contains the length btw

It's exactly your own code, just a little refactored - I removed all unneccesary stuff etc, nothing more..

Edit: Now fixed to verify stream status & prevent stack overflow :)

Edit II: Changed std::cin.good() && !std::cin.eof() to std::cin. Btw: why does cin have a conversion to void* and not to a bool?


Is there any reason you are not using std::string and std::getline? You should think twice or even thrice before writing your own extraction operator - formatted input is not a particularly useful feature of C++ (or of C, come to that).


In any case, the code is broken. It doesn’t handle input failures, which may be fatal since your code can enter an infinite loop. If you encapsulate stream reading operations, you must take care to test whether the stream is in a valid state.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜