如果字符串在 C++ 中有字母,如何使用 stoi 和 return false?

How to use a stoi, and return false if the string has a letter in c++?

所以,我在C++中有这段代码,需要使用stoi来测试String(a)是否有字母,如果没有,将数字发送给int,如果有return 错误。

我的代码

void main(){

  string a = "a1321";
  int b;
  if (stoi(a)){
    b = stoi(a);
    cout << b << endl;
  }
  else cout << "ERROR"<< endl;

  system("pause");

}

有人能帮忙吗?

你可以这样写函数:

bool try_stoi(int & i, const string & s){
    try {
        size_t pos;
        i = stoi(s, &pos);
        return pos == s.size();
    }
    catch (const std::invalid_argument&) {
         return false;
    }
}

因为 stoi return 解析后的整数值不能直接使用 return 值来检查正确性。

您可以捕获 std::invalid_argument 异常,但它可能太多了。如果你不介意使用 strol C 函数而不是 std::stoi 你可以做类似

bool isNumber(const std::string& str)
{
  char* ptr;
  strtol(str.c_str(), &ptr, 10);
  return *ptr == '[=10=]';
}

它利用了函数将第二个 char** 参数设置为传递的字符串中的第一个非数字字符的事实,对于仅包含数字的字符串应该是 '\0'。

//使用此代码

int main() {
  string a;
  
  cin >> a;
  
  try {
    int b;
    b = stoi(a);
    cout << b;
  } 
  catch (exception e) {
    cout << "string not converted";
  }

  return 0;
}