【问题标题】:Check if string is not a number before converting it to a int [duplicate]在将字符串转换为 int 之前检查字符串是否不是数字 [重复]
【发布时间】: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) &gt;&gt; price; 如果字符串不是数字,我希望它在控制台打印一行。

【问题讨论】:

  • if(!(stringstream(mystr) &gt;&gt; quantity)) cout &lt;&lt; "Not a number" &lt;&lt; std::endl;

标签: c++


【解决方案1】:

您可以通过检查输入流的fail() 位来了解int 的读取是否成功:

getline (cin,mystr); //gets user input
stringstream priceStream(mystr);
priceStream >> price;
if (priceStream.fail()) {
    cerr << "The price you have entered is not a valid number." << endl;
}

Demo on ideone.

【讨论】:

  • 你也用bad(),有什么区别?
  • @herohuyongtao 这是我在输入演示时犯的错误,现在已修复:两个地方都应该是fail()
【解决方案2】:

如果您想检查用户输入的价格是否为浮点数,您可以使用boost::lexical_cast&lt;double&gt;(mystr);,如果它抛出异常则您的字符串不是浮点数。

【讨论】:

    【解决方案3】:

    它会为您的代码添加一些内容,但您可以使用 cctype 中的 isdigit 解析 mystr。该库的功能是here。如果字符串中的字符不是数字,isdigit(mystr[index]) 将返回 false。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      • 2017-05-04
      • 2021-07-10
      • 2023-03-31
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      相关资源
      最近更新 更多