I have a user input an integer... But if it's really long, it throws an exception and starts looping infinitely. How would I make it cut the number after the first 7 digits and only use that? Like, if I inputted 654897654321648435435135813513843513543514, it would only accept 6548976. Please help.

Recommended Answers

All 4 Replies

get the data as a std::string then convert it to integer.

Thanks. That's what I was told, but I wasn't entirely sure.

Another way to do it is to clear the input buffer after cin returns. See this thread how to do that. You will probably also have to clear cin's error flags, such as cin.clear().

As suggested the easiest way to achieve it is using std::string as follows:

std::string getClampedInput(const int maxSize){
 string str;
 getline(cin,str);
 int clampedSize = maxSize > str.size() ? str.size() : maxSize; //make sure maxSize is not greater than input size
 return str.substr(0,maxSize);
}

another way is to do it is using cin.get, but the above method is the easiest.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.