我寫了一個程序,詢問用戶有多少輛汽車目錄。該程序使用新創建一個動態陣列的許多汽車結構。接下來,它應該提示用戶輸入每個結構的製造和年份信息。爲什麼我應該在這裏使用這個「while」表達式?那個表達意味着什麼?
但是,我之前錯過了「WHILE」表達式。程序直接運行到最後。該結果如下:
和預期的結果應該是
什麼問題發生?當我需要用數字數據交替讀取字符串時該怎麼辦?
這裏是我的源代碼:
#include <iostream>
#include <string>
using std::string;
// create car structure
struct car
{
string make;
int year;
};
int main()
{
using std::cout;
using std::cin;
using std::endl;
int num;
cout << "How many cars do you wish to catalog? ";
cin >> num;
while (cin.get() != '\n')
;
// create a dynamic array
car * catalog = new car [num];
//store
for (int i = 0; i < num; ++i)
{
cout << "Car #" << i + 1 << ":\n";
cout << "Please enter the make: ";
getline(cin, catalog[i].make);
cout << "Please enter the year made: ";
cin >> catalog[i].year;
while (cin.get() != '\n')
;
}
//display
cout << "Here is your collection: \n";
for (int i = 0; i < num; ++i)
{
cout << catalog[i].year << " " << catalog[i].make << endl;
}
delete [] catalog;
return 0;
}
那'while'聲明跳到輸入行結束的方式。 –
用'cin.ignore(numeric_limits :: max(),'\ n')' –
user4581301
可能會節省一點時間(但不能打字)謝謝! @Captain Obvlious –