【发布时间】:2014-01-22 02:08:04
【问题描述】:
我有一个终端应用程序,它获取用户输入将其存储在字符串中,然后将其转换为 int。问题是,如果用户输入任何不是数字的内容,则转换将失败,并且脚本继续运行,而没有任何迹象表明该字符串尚未转换。有没有办法检查字符串是否包含任何非数字字符。
代码如下:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string mystr;
float price=0;
int quantity=0;
cout << "Enter price: ";
getline (cin,mystr); //gets user input
stringstream(mystr) >> price; //converts string: mystr to float: price
cout << "Enter quantity: ";
getline (cin,mystr); //gets user input
stringstream(mystr) >> quantity; //converts string: mystr to int: quantity
cout << "Total price: " << price*quantity << endl;
return 0;
}
就在此处转换之前:stringstream(mystr) >> price; 如果字符串不是数字,我希望它在控制台打印一行。
【问题讨论】:
-
if(!(stringstream(mystr) >> quantity)) cout << "Not a number" << std::endl;
标签: c++