2016-07-11 251 views
0

我正在開發一個簡單的酒店預訂項目,但輸入名稱後無法打印客戶名稱和付款類型。這是我輸入的一段代碼。如何在C++中打印char數組

cout << "Please enter the customer name: " << endl; 
cin >> customername1; 
cin.getline(customername1,100,'\n'); 
fflush(stdin); 
cout << "Please enter the payment type: " << endl; 
cin >> paymenttype; 
cin.getline(paymenttype,100,'\n'); 
fflush(stdin); 
cout << "How many days would you like to stay: " << endl; 
cin >> days; 
room_income = days * 30; 
count_room++ ; 
count_customer1++ ; 
customer_name1[single]= new char [strlen(customername1)+1]; 
strcpy(customer_name1[single],customername1); 
payment_type[single]= new char [strlen(paymenttype)+1]; 
strcpy(payment_type[single],paymenttype); 
cout << "Room number : " << single << endl<< endl; 
cout << "Customer name : "<< customer_name1 << endl << endl; 
cout << "Payment type : "<< payment_type << endl<< endl; 
cout << "Number of day for accomodation :"<< days << endl<< endl; 
cout << "Income for this room : "<< room_income<< endl<< endl; 

顯示客戶名稱和付款類型的一些隨機數字和字母。我如何正確書寫它們?

+2

什麼是說'customername1'的類型?爲什麼要讀兩遍? (''''和'getline') –

+6

'new char [strlen(customername1)+1];'wooooah there!怎麼樣一個不錯的'std :: string'遊戲呢? –

+1

'cin >> customername1;'已經讀取輸入,你爲什麼要'cin.getline(customername1,100,'\ n');''之後?? –

回答

1

對於客戶名稱和付款類型,您嘗試打印數組而不是一個元素。由於數組基本上只是指向第一個元素的指針,因此您將得到一個「隨機數」,即內存地址。

嘗試:

cout << "Customer name : "<< customername1 << endl << endl; 
cout << "Payment type : "<< paymenttype << endl<< endl; 

而當你已經有了工作,按照意見和考慮的std :: string和載體...

+0

是的你是對的,我也認爲cin.getline(customername1,100,'\ n')是不必要的 – erengsgs

+0

@NathanOliver:不,仔細查看變量的名字... OP,你對你的評論是正確的。 – DrDonut

+0

呼叫良好。有點下劃線。 – NathanOliver