简体   繁体   中英

Input validation for reading in vector of ints

I'm reading in from the user a vector of ints and I'm trying to do some input validation so that if the user enters a letter it changes it to a 0. Here is what I have.

 for(int i=0; i < columns;i++)      
                {
                    int temp3;
                    cin >> temp3;
                    if (temp3 > 100 or temp3 < 0)
                        temp3 = 0;
                    if (isalpha(temp3))   //run-time error here 
                        temp3 = 0;

                    newstu.push_back(temp3);


                }

the commented line is the problem but since it's a run-time error. I'm not sure why this is wrong/doesn't work. Any ideas? Thanks in advance

if you have access to boost, you could also try to use a try/catch design.

You have an example there: https://www.boost.org/doc/libs/1_55_0/doc/html/boost_lexical_cast/examples.html

try
{
   args.push_back(lexical_cast<int>(temp3));
}
catch(const bad_lexical_cast &)
{
  args.push_back(0);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM