2016-04-23 10 views
0

配列に文字の行を入力する際に​​問題があります。ここに主要な問題があります。私はサイズ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; 

}

+1

あなたが試行したことを表示します。 – Unimportant

+1

いいえ、あなたの質問を編集し、あなたのコードを質問の一部として表示してください。 –

+0

@SamVarshavchik申し訳ありませんが、私はこれで初めてです: '3 –

答えて

0

代わりにC++ std::stringを使用してください。

std::string name, id; 

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

あなたid sが非常に長いものではなく、数字のみが含まれている場合は、あなたが数字にそれらを読むことができる:

unsigned long id; 

std::cin >> id; 
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を渡す必要があります。配列では、配列、容量、サイズを渡す必要があります。ところで、配列に '\ 0'終端文字を保持しないと、未定義の動作が発生します。

関連する問題