// File: str2int.cpp // Demo to convert string to int using istringstream #include #include #include using namespace std; void main() {int n; string line; cout << "Enter a string that might represent an integer >"; cout.flush(); getline(cin,line); istringstream str2int(line); if (str2int.good()) { str2int >> n; // The peek function looks at the next char in a stream char peekChar=str2int.peek(); // If that char is not whitespace and there is a char to peek at, fail if (peekChar!=' ' && peekChar!='\n' && peekChar!=-1) // peekChar==-1 means nothing left to peek at cout << "Conversion error"; else cout << n << endl; } }