简体   繁体   English

(cin >> int).get()在Xcode中没有正常工作(4.3.3)

[英](cin >> int).get() doesn't properly work in Xcode(4.3.3)

I'm currently working on the book "C++ Primer Plus" and doing some of the programming excersis. 我目前正在编写“C ++ Primer Plus”一书并完成一些编程练习。 As it seems, I'm having a problem with Xcode(4.3.3) because following code doesn't work how it's supposed to work: 看起来,我遇到了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;
}

The problem is, I don't have the chance to enter any maker. 问题是,我没有机会进入任何制造商。 The program directly goes to the point where I have to enter the year, even though I'm using "(cin >> nCars).get();" 该程序直接进入我必须输入年份的点,即使我正在使用“(cin >> nCars).get();” to get rid of the newline character. 摆脱换行符。

Am I overlooking something? 我忽略了什么吗?

Thanks in advance! 提前致谢!

I suspect that you may be running on windows and the two-byte newlines are hitting you. 我怀疑你可能在Windows上运行,并且双字节换行符正在打击你。 You may be able to improve things (for lines that aren't ridiculously long) with ignore: 你可以用ignore来改进(对于那些不长得多的行):

cin >> nCars;
cin.ignore(1024, '\n');

Note that since you rely on stream numeric processing, entering a non-numeric year such as QQ will result in the programming just finishing without asking for any more input. 请注意,由于您依赖于流数字处理,因此输入非数字年份(例如QQ将导致编程刚刚完成而无需再请求输入。

You don't need to do math on the years so treat them as strings instead of integers. 您不需要对这些年份进行数学运算,因此将它们视为字符串而不是整数。 Then if you need to you can do validation of each year after you get the input. 然后,如果您需要,您可以在获得输入后每年进行验证。

Ok, guys..I found the problem. 伙计们......我发现了问题。 The console within Xcode doesn't work as expected when using cin.get(). 使用cin.get()时,Xcode中的控制台无法正常工作。 I tried the same code in the terminal as well as with Visual Studio (Win 7) and the program works perfectly. 我在终端以及Visual Studio(Win 7)中尝试了相同的代码,程序运行良好。

Anyway, thank you all for your advices. 无论如何,谢谢大家的建议。 I'll try consider them the next time. 我会在下次尝试考虑它们。 :) :)

Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM