检查字符串是否是数字,然后将该数字转换为 int?
Checking if a string is a number, then converting that number to an int?
"程序"是接受输入,然后将字符串吐出到单独的行中,在这种情况下,所有数字都要乘以二。
当在空格后输入数字时,会出现我的问题。 例
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;
}
相关文章:
- 将数字转换为字母(例如:123 转换为一二三)
- 将数字转换为单词
- 使用if-else将数字转换为单词
- 将数字转换为填充字符串
- 编译时间文本到数字转换 (atoi)
- 在 c++ 中将数字转换为矢量数组的函数
- 奇怪的数字转换C++
- 用C++将浮点数字转换为本地化字符串
- 如何将ASCII数字转换为从文件中提取的整数
- 检查字符串是否是数字,然后将该数字转换为 int?
- 将 MPFR 数字转换为字符串并返回
- 如何将数字转换为整数向量?
- 如何在C++中将数字转换为链表
- 如何将字符串中的多个数字转换为整数
- 有问题将数字转换为罗马数字
- 这个给定的代码应该将给定的数字转换为尽可能滞后的数字,no.by 用 9.It 替换合适的数字是行不通的
- 将两位数字转换为低内存表示的最快方法
- 视觉 如何将混合的字母和数字转换为仅字母?C++
- 如何在 c++ 中将十六进制数字转换为字符
- 如何将字符串数字转换为各个数字的整数数组