C ++将字符串转换为整数 [英] C++ converting string into integer
问题描述
问候大家,
我目前正在尝试制作一个程序,该程序可以将用户输入的字符串转换为int.
我希望该整数最大为4,294,967,295.我目前正在使用stoi将字符串转换为无符号的int,但是每次我尝试输入10位数字的数字时,都会弹出错误"abort()已被调用".我来这里是为了弄清楚我的代码出了什么问题.
Greetings everybody,
I am currently trying to make a program that can will convert a string that is input by a user into a int.
I want this integer to be up to 4,294,967,295. I am currently using stoi to convert the string into an unsigned int, but everytime I try to input a number that is 10 digits long, an error "abort() has been called" pops up. I''ve come here to figure out what the issue is with my code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "4,294,967,295" << endl;
string numberString;
getline(cin, numberString);
unsigned int number = stoi(numberString);
cout << number << endl;
return 0;
}
提前谢谢!
问候
我尝试过的事情:
我尝试使用无符号的长整型,双精度型,但都无法正常运行
Thanks in advance!
Regards
What I have tried:
I''ve tried using unsigned long, double but both do not work
推荐答案
那个4 ....数字是2 ^ 32-1,超出了范围为32位int,返回类型为stoi
.它是可以表示为UNSIGNED int的最大数字,因此您需要使用stoul
或其他将返回大于有符号int的数字的东西.另外,也可以将sscanf用于%u之类的转换或更大的转换.
That 4.... number is 2^32-1, which is beyond the range of a 32 bit int, the return type ofstoi
. It is the largest number that can be expressed as an UNSIGNED int, so you need to usestoul
or something else that will return numbers bigger than a signed int. Alternatively, you could use sscanf with a conversion like %u or something "bigger".
stoi
用于转换带符号的32位整数,该整数可以保存的最大值为2,147,483,647.您应该捕获从stoi
引发的out_of_range异常.并且请删除您的数字字符串中的逗号.
std :: stoi,std :: stol,std :: stoll-cppreference.com [ ^ ]
另一种选择是使用字符串流将您的字符串转换为数字.
stoi
is for converting signed 32 bit integer whose maximum value it can hold is 2,147,483,647. You should catch the out_of_range exception thrown fromstoi
. And please remove the commas in your number string.
std::stoi, std::stol, std::stoll - cppreference.com[^]
Another alternative is to use string streams to convert your strings to numbers.
#include <sstream>
#include <iostream>
int main()
{
unsigned int n = 0;
std::istringstream oss("4294967295");
oss >> n;
std::cout << n << std::endl;
return 0;
}
这篇关于C ++将字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!