Могу ли я проверить, является ли введенное значение строкой или целым числом в C ++

0

Я хочу проверить, введенное пользователем значение является строкой или целым числом. Вход принимается как cin >> obj [i].int_code; в коде.

Проблема состоит в том, что если пользователь вводит какую-либо строку вместо целого числа, программа переходит в бесконечный цикл.

#include<iostream>
using namespace std;
class item{

public:
    int int_code;
    string str_name;
};
item obj[100];

main(){
    int c,i=0,int_cd,n=0,pos=0;

    do{
        cout<<"\n_______YOUR OPTIONS________\n";
        cout<<"\t1.Add Item\n\t2.View Item\n\t3.Delete Item\n\t4.List Item\n\t5.Exit\n";
        cout<<"Enter your choice: ";
        cin>>c;

        switch(c){
            case 1://Add Item
                cout<<"Enter the item_code: ";

                cin>>obj[i].int_code;

                cout<<"Enter the item_name: ";
                cin>>obj[i].str_name;
                i++;
                n++;
                break;
            case 2://View item
                cout<<"Enter the item_code: ";
                cin>>int_cd;
                for(i = 0;i < n;i++)
                    if(int_cd == obj[i].int_code)
                        cout<<obj[i].int_code<<"\t"<<obj[i].str_name<<"\n";
                break;
            case 3://Delete Item
                cout<<"Enter the item_name: ";
                cin>>int_cd;

                for(i = 0;i < n; i++)
                    if(int_cd==obj[i].int_code)
                        pos=i;

                for(i=pos;i<n;i++){
                    if(obj[i].int_code != NULL)
                        obj[i]=obj[i+1];
                    else
                        obj[i].int_code=NULL;
                        //obj[i].str_name=;
                }
                n--;
                break;
            case 4://list Item
                for(i=0;i<n;i++)
                    cout<<obj[i].int_code<<"\t"<<obj[i].str_name<<"\n";
                break;
            default:
                cout<<"Enter any number between 1 to 5";
                break;
        }
    }while( c != 5 );
}

    enter code here
Теги:
class
string
integer
cin

5 ответов

2

Использовать boost::lexical_cast:

    string str;
    cin >> str;
    int val;
    try
    {
        val = lexical_cast<int>(str));
    }
    catch(const bad_lexical_cast &)
    {
        // not an int
    }
  • 0
    +1 У меня много времени для lexical_cast. Это относительно быстро и приятно читать.
  • 1
    Проблема в том, что вам нужен блок try...catch . Вы действительно хотите что-то, что позволяет вам проверить на наличие ошибки с помощью простого if .
Показать ещё 3 комментария
1

изменить свою линию

из

cin>>c;

в

c = -1;
cin>>c;

if (c < 1 || c > 5)
{
    cout<<"Enter any number between 1 to 5";
    continue;
}
  • 0
    Как это решает проблему?
  • 0
    int c; CIN >> с; если пользователь вводит строку, cin не может присвоить ее c, поскольку c имеет тип int. c будет содержать старое значение (может быть 1..5 или какой-то мусор в случае первого раза). Это приводит к бесконечному циклу while. Здесь проблема решена непосредственно перед оператором cin >> c, я назначил c = -1; здесь c будет иметь значение -1 в случае, если пользователь введет любое строковое значение, и «Введите любое число от 1 до 5» будет напечатано на консоли
1

В качестве альтернативы lexical_cast вы можете сделать что-то вроде этого:

#include <iostream>
static const int ZERO_ASCII = 48;
static const int MAX_OPTION = 5;
static const int MIN_OPTION = 1;
int main() {
    std::string input;
    std::cin >> input;
    if(input.length() > 1 ){
        std::cout << "Not correct length" << input << std::endl;
        return -1; // in your case use "continue"
    }
    char val = *(input.c_str());
    int intVal = static_cast<int>(val);
    int option = intVal - ZERO_ASCII; // see your printed out ASCII chart :)
    if (MIN_OPTION > option || option > MAX_OPTION) {
        std::cout << "Not valid value " << option << std::endl;
        return -1; // in your case use "continue"
    }
    std::cout << "selected option " << option << std::endl;
}

Это допустимый вариант из-за нескольких вещей:

  1. Ваш пользователь дает вам случайное строковое значение. Поэтому ваша программа должна читать случайное строковое значение и затем проверять его.
  2. Вы можете применить любой вид проверки, который вам нравится. Здесь я проверил, что это один символ длинный, и что это значение представляет собой ASCII-представление цифры и цифра находится в диапазоне.
  3. Для простой проверки это менее дорогостоящим образом, если заявления, чем исключения, поскольку пользователи часто дают вам информацию об мусоре.
0

Обратите внимание, что часть "проверка, если введенное значение является строкой или целым числом" является проблемой в нескольких частях приложения. А именно, случаи 1, 2 и 3 все ожидают целые входы (случай 3 рассматривается ниже). Методы get_int и get_string адаптированы из того, как сделать cin брать только числа. Первоначально я создал метод get_int; однако я обнаружил, что get_string также необходимо, иначе "Ввод вашего выбора" произойдет дважды, а не один раз, после того, как "Добавить элемент", случай 1, был завершен.

Кроме того, "Удалить элемент", случай 3, имел ошибку в формулировке, поскольку запрос предназначен для "item_name"; однако cin ожидает целое число, а не строку, поэтому я изменил формулировку там, а также метод ввода. Я прокомментировал выражение cout по умолчанию, поскольку он теперь избыточен, если предыдущий случай не применим к введенному значению. Наконец, в коде "Удалить элемент" все еще была ошибка (исправлено ниже), так как запрос на удаление item_code 2 удалит item_code 1, если в этом есть только элемент, из-за которого не будет сброшен.

#include <iostream>
#include <limits>
#include <sstream>
#include <string>

using namespace std;

class item
{

    public:
       int int_code;
       string str_name;
};
item obj[100];

string get_string(string message)
{
    string line = "";
    string rs = "";
    cout << message;
    getline(cin, line);
    stringstream ss(line);
    ss >> rs;
    return rs;
}

int get_int(string message)
{
    int ri = -1;
    string line = "";
    bool isint = false;

    while (!isint)
    {
        cout << message;
        getline(cin, line);
        stringstream ss(line);
        if (ss >> ri)
        {
            if (ss.eof())
            {   // Success
                isint = true;
            }
        }
    }
    return ri;
}

int main (int argc, char ** argv)
{
    int c,i=0,int_cd,n=0,pos=0;
    do
    {
        cout<<"\n_______YOUR OPTIONS________\n";
        cout<<"\t1.Add Item\n\t2.View Item\n\t3.Delete Item\n\t4.List Item\n\t5.Exit\n";
        c = get_int("Enter your choice: ");

        switch(c){
            case 1://Add Item
                obj[i].int_code = get_int("Enter the item_code: ");
                obj[i].str_name = get_string("Enter the item_name: ");
                i++;
                n++;
                break;
            case 2://View item
                int_cd  = get_int("Enter the item_code: ");
                for(i = 0;i < n;i++)
                    if(int_cd == obj[i].int_code)
                        cout<<obj[i].int_code<<"\t"<<obj[i].str_name.c_str()<<"\n";
                break;
            case 3://Delete Item
                int_cd  = get_int("Enter the item_code: ");
                pos = -1;
                for(i = 0;i < n; i++)
                    if(int_cd==obj[i].int_code)
                        pos=i;
                // ensure specified item_code is found before deleting an item
                if(pos != -1)
                {
                    for(i=pos;i<n;i++)
                    {
                        if(obj[i].int_code != NULL)
                            obj[i]=obj[i+1];
                        else
                            obj[i].int_code=NULL;
                            //obj[i].str_name=;
                    }
                    n--;
                }
                break;
            case 4://list Item
                for(i=0;i<n;i++)
                    cout<<obj[i].int_code<<"\t"<< obj[i].str_name.c_str() <<"\n";
                break;
            default:
                //cout<< "Enter any number between 1 to 5" << endl;
                break;
        }
    } while( c != 5 );
    return 0;
}
0

Выход, если не номер:

#include<iostream>
using namespace std;
class item{

public:
  int int_code;
  string str_name;
};
item obj[100];

main(){
  int c,i=0,int_cd,n=0,pos=0;

  do{
    cout<<"\n_______YOUR OPTIONS________\n";
    cout<<"\t1.Add Item\n\t2.View Item\n\t3.Delete Item\n\t4.List Item\n\t5.Exit\n";
    cout<<"Enter your choice: ";
    cin >> c;
    if (!cin) break;
    switch(c){
    case 1://Add Item
      cout<<"Enter the item_code: ";
      cin>>obj[i].int_code;
      cout<<"Enter the item_name: ";
      cin>>obj[i].str_name;
      i++;
      n++;
      break;
    case 2://View item
      cout<<"Enter the item_code: ";
      cin>>int_cd;
      for(i = 0;i < n;i++)
    if(int_cd == obj[i].int_code)
      cout<<obj[i].int_code<<"\t"<<obj[i].str_name<<"\n";
      break;
    case 3://Delete Item
      cout<<"Enter the item_name: ";
      cin>>int_cd;

      for(i = 0;i < n; i++)
    if(int_cd==obj[i].int_code)
      pos=i;

      for(i=pos;i<n;i++){
    if(obj[i].int_code != 0)
      obj[i]=obj[i+1];
    else
      obj[i].int_code= 0;
    //obj[i].str_name=;
      }
      n--;
      break;
    case 4://list Item
      for(i=0;i<n;i++)
    cout<<obj[i].int_code<<"\t"<<obj[i].str_name<<"\n";
      break;
    default:
      cout<<"Enter any number between 1 to 5";
      break;
    }
  }while( c != 5 );
}
  • 0
    Большой!! (У)! \ М / !! Это работало нормально. Спасибо.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню