我目前正在編寫「C++ Primer Plus」一書,並正在做一些編程工作。 因爲它似乎,我在和Xcode(4.3.3)的一個問題,因爲下面的代碼不起作用它是如何工作的:(cin >> int).get()在Xcode中不正常工作(4.3.3)
#include <iostream>
#include <string>
struct car
{
std::string maker;
int year;
};
int main()
{
using namespace std;
cout << "How many cars do you wish to catalog? ";
int nCars;
(cin >> nCars).get();
car* aCars = new car[nCars];
for (int i = 0; i < nCars; i++)
{
cout << "\nCar #" << (i + 1) << endl;
cout << "Please enter the make: ";
getline (cin, (aCars + i)->maker);
cout << "\nPlease enter the year made: ";
(cin >> (aCars + i)->year).get();
}
cout << "Here is your collection: \n";
for (int i = 0; i < nCars; i++)
{
cout << (aCars + i)->year << " " << (aCars + i)->maker << endl;
}
delete [] aCars;
return 0;
}
的問題是,我沒有機會進入任何製造商。該程序直接進入了我必須輸入年份的點,即使我使用「(cin >> nCars).get();」擺脫換行符。
我可以俯視嗎?
在此先感謝!
您不得在不檢查返回值的情況下執行輸入操作。在這個階段沒有任何意義。 –
使用'std :: vector'代替'new T []''。 –
GManNickG
對不起,我應該提到,本書中的exersise說程序應該使用「new」來創建一個動態數組。 exerscise本身很簡單,但我不知道爲什麼上面的代碼無法正常工作。 – milchschaum