我目前正在编写“C++ Primer Plus”一书并进行一些编程练习。 看起来,我在使用 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();”摆脱换行符。
我是不是忽略了什么?
提前致谢!
最佳答案
我怀疑您可能在 Windows 上运行,并且两个字节的换行符正在攻击您。您可以通过忽略来改进一些东西(对于不是很长的行):
cin >> nCars;
cin.ignore(1024, '\n');
请注意,由于您依赖于流式数字处理,因此输入非数字年份(例如 QQ
)将导致编程刚刚完成,而无需再要求任何输入。
您不需要对年份进行数学计算,因此将它们视为字符串而不是整数。然后,如果需要,您可以在获得输入后对每年进行验证。
关于c++ - (cin >> int).get() 在 Xcode(4.3.3) 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12181525/