Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

C++
#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
Posted
Updated 7-Jul-18 23:16pm

That 4.... number is 2^32-1, which is beyond the range of a 32 bit int, the return type of stoi. It is the largest number that can be expressed as an UNSIGNED int, so you need to use stoul 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".
 
Share this answer
 
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 from stoi. 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.

C++
#include <sstream>
#include <iostream>

int main()
{
	unsigned int n = 0;
	std::istringstream oss("4294967295");
	oss >> n;
	std::cout << n << std::endl;
    return 0;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900