So i am trying to have the user only receive integers when they are choosing an array size but the numbers don't add up if I were to to type in a floating number. If they type in letters then the right error message pops up but I can't get right if they type in 4.4, 1.21, etc. the way I currently have it. Am I doing this hard way? Would I be better off using stringstream? I left out a chunk of the code.
#include <iostream>
#include <limits>
int main()
{
const int CAPACITY = 100;
int choice;
int size = 0;
double array[CAPACITY];
do
{
std::cout << "Hey there! Pick an option" << std::endl;
std::cout << "Hit 1 to do some math " << std::endl;
std::cout << "Hit 2 to quit" << std::endl;
std::cin >> choice;
if (choice == 1)
{
std::cout << "Choose the size of your array. The array can be set to capacity of 100" << std::endl;
//std::cin >> size;
if((std::cin >> size).fail()) {
std::cin.clear();
std::cin.ignore(1000, '\n');
std::cout << "Invalid input" << std::endl;
continue;
}
if(size <= 0){
std::cout << "Sorry, that not a valid option" << std::endl;
continue;
}
if (size > CAPACITY){
std::cout << "Sorry, that is too large" << std::endl;
continue;
}
if (size < CAPACITY){
std::cout << "Add some numbers to your array" << std::endl;
for (int i=0; i < size; i++)
{
std::cout << "Enter a number: " << std::endl;
std::cin >> array[i];
}
As you mentioned std::stringstream is a solution in this case
std::string s;
std::cin >> s;
std::stringstream ss(s);
int n;
// Only accept if stringstream is empty after parsing
if(! (ss >> n) || !ss.eof() )
std::cerr << "something's fishy with '" << s << "'" << std::endl;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.