输入一行字符

时间:2016-04-23 17:07:00

标签: c++ arrays

我遇到向数组输入一行字符的问题。这是主要问题。我已经声明了一个大小为50的数组,我想输入我的名字,但是当我使用循环输入它时它不会存储它循环只是继续运行直到我输入直到50个字符:/ 我该如何避免这个问题? 用一个例子来解释谢谢:)

           void option1()//here user inputs the data
        {
         string name[20];
         string date[20];
         string from[20];
         string to[20];
         string id_no[20];



        system("CLS");
        cout << "\n\n\t\tEnter your seat no.:  ";
        cin >> seat;

        while(seat>32 || seat<0)
        {
            cout << "\n\t\tThere are no seats greater than 32 please type in again: ";
            cin >> seat;
        }
        cout << "\t\tEnter your name: ";
        cin >> name[seat];

        cout << "\t\tEnter Your date: ";
        cin >> date[seat];

        cout << "\t\tEnter your ID No. :";
        cin >> id_no[seat];

        cout << "\t\tWhere do you want to travel:\n ";

        cout << "\t\t\tFrom: ";
        cin >> from[seat];

        cout << "\t\t\tTo: ";
        cin >> to[seat];

        system("CLS");

        cout << "\n\n\t\tTHANK YOU! YOUR SEAT HAS BEEN BOOKED\n";
        getchar();
        system("CLS");
        }
      void option2()//From here how can i bring the data to this funciton?
   {
       string name[20];
       string date[20];
       string from[20];
       string to[20];
       string id_no[20];
      cout << "\t\t\tEnter your seat number: ";
      cin >> seat;

        cout << "\t\tYour Name: " << name[seat] << endl;

        cout << "\t\tYour Date of travelling: " << date[seat] << endl;

       cout << "\t\tYour ID no. : " << id_no[seat] << endl;

       cout << "\t\tTravelling From: " << from[seat] << endl;

       cout << "\t\tTravelling To: " << to[seat] << endl;

}

2 个答案:

答案 0 :(得分:0)

你这样做的方式不对。

改为使用C ++ std::string

std::string name, id;

std::cin >> name >> id; // so easy!

如果id不长并且只包含数字,您可以将它们读成数字:

unsigned long id;

std::cin >> id;

答案 1 :(得分:0)

您可以使用std::string类来避免此问题:

std::string name;
std::cout << "Enter name: ";
std::getline(std::cin, name);

如果您必须使用字符数组,则可以使用getline

#define MAX_NAME_LENGTH 50
char array[MAX_NAME_LENGTH];
cin.getline(&array[0], MAX_NAME_LENGTH, '\n');

如果使用字符数组,则会遇到许多问题。首选方法是使用std::string。例如,std::string管理内存(分配和删除),以及按需扩展。您只需将std::string传递给函数,因为它具有length成员函数。对于数组,您需要传递数组,容量和大小。顺便说一句,如果你不保持&#39; \ 0&#39;终止数组中的字符,未定义的行为结果。