检查字符串是否是数字,然后将该数字转换为 int?

Checking if a string is a number, then converting that number to an int?

本文关键字:数字 转换 int 然后 字符串 是否是 检查      更新时间:2023-10-16

"程序"是接受输入,然后将字符串吐出到单独的行中,在这种情况下,所有数字都要乘以二。

当在空格后输入数字时,会出现我的问题。 例

Sentence: 12 fish

输出:

24     
fish

但。。。

Sentence: there are 12

输出:

there
are
0

我编写的程序:

#include <iostream>
#include <string>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
using namespace std;
int main()
{
string str;
int number = 811;
cout << "Sentence: ";
getline(cin,str);
istringstream iss(str);
while(iss)
{
bool ree = 0;
string word;
iss >> word;
if(isdigit(word[0]))
{
stringstream(str) >> number;
number = (number * 2);
cout << number << endl;
ree = 1;
number = 911;
}
if(!ree)
{
cout << word << endl;
}
ree = 0;
}
}

希望这是我没有看到的小东西! 感谢您提前提供的帮助。

问题是

stringstream(str) >> number;

从初始句子创建一个新的字符串流,然后尝试从中提取到number中。当然,这将失败(因为句子中的第一个单词不是数字(。如果你想知道为什么number设置为 0,那是因为在失败时,stringstream::operator>>将参数归零(自 C++11 以来(。

">如果提取失败,则写入值为零并设置故障位。">

在C++11之前,它保持了论点不变。有关更多详细信息,请参阅文档。

正确的方法是使用从字符串到int(或long(的转换,即std::stoi,并将该行替换为

try{
number = std::stoi(word); 
}
catch(std::exception& e){
std::cout << "error converting" << 'n';
}

使用stoi像这样解析输入:

int num = std::stoi(input);

使用stoi很容易,您可以通过以下方法懒惰地捕获异常:

if(!stoi(string)){
std::cout << "caught a non integer string" << endl;
}