c++ - Using istringstream() to distinguish between "0" and non-numerical string -


i trying make program play poker. when betting player should enter integer number new bet. prevent errors when mistypes , enters string code intended take in string, check if number, , if not ask player enter valid bet.

the code below attempt @ making function using istringstream function convert string betstring int.

istringstream returns 0 if string has no number in it. betstring invalid entry if number less 0 or if contains no numbers. if betstring "0" valid bet.

if betstring mixed letters , numbers (e.g. j96kp) "j96kp" assumed indicate bet of 96 simplicity valid.

the problem comes when enter betstring equal "0". code interprets invalid bet. have checked logic operators , not understand why code not take "0" valid bet.

can spot problem arising?

#include <stdlib.h> #include <stdio.h> #include <sstream> #include <string>  using namespace std;  int requestbet() {     int newbet;     string betstring;     int validbet = 0;     while(!validbet)     { //loop until valid bet entered         cin >> betstring;         validbet = 1; //assume bet valid test         istringstream(betstring) >> newbet;          if(((newbet == 0) && (betstring.at(0) != 0)) || (newbet < 0))         {             cout << "enter valid bet" << endl;             validbet = 0;         }     }     return newbet; }  int main() {     int number;     cout << "enter bet" << endl;     number = requestbet();     return 0; } 

betstring.at(0) != 0 not expect do. want compare characters, is, see if first character '0', have put in there. is, code sees whether fist char has numerical value 0 (which '\0').


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -