云青兮欲雨 2015-10-13 09:13 采纳率: 0%
浏览 4836

C++字符串和数字混合输入问题

#include <iostream>

using namespace std;
int main()
{
struct Car
{
    char maked[20];
    int year;

};
unsigned int i;
cout << "How many cars do you wish to catalog ? ";
cin >> i;
Car *car = new Car[i]; 
for (int k = 0; k < i; k++)
{
    cout << "Car #" << k + 1 << ":" << endl;
    cout << "Please enter the make : ";
    cin.getline(car[k].maked,20);
    //cin.get();
    cout << "Please enter the year made: ";
    //cin.get();
    cin>> car[k].year;
    cin.get();
}
cout << "Here is your collection : " << endl;
for (int k = 0; k < i; k++)
{
    cout << car[k].year << "\t" << car[k].maked << endl;
}
delete[]car;

        return 0;
}

图片说明
为什么for循环内的第一次不让输入字符串啊?

  • 写回答

5条回答 默认 最新

  • abc2247727 2017-09-09 13:24
    关注

    这个问题我今天在学习 C++ 的时候也遇到了,这个问题的原因是因为 cin 在读取年份的时候,将回车键生成的换行符留在了输入队列中。
    问题是以下这行代码。

    cout << "How many cars do you wish to catalog ? ";
    cin >> i;
    

    输入这行之后我们是按了 键换行符的,所以这个换行符被读取进了下面的 cin.getline(...),相当于 cin.getline(...) 读取了一个 。

    同样下面的循环内部的cin 也一样,**要解决 这个的办法就是在每次输入数字的后面加上代码 cin.get();** 这样子就能把输入的 保存在 cin.get()里面了。

    下面是我自己打的代码,我测试了是可以用的

     #include <iostream>
    
    using namespace std;
    
    struct car
    {
        string production;
        int proYear;
    };
    
    int main()
    {
        int c_num;
    
        cout << "This program will show up your collection, my Lord" << endl;
        cout << "How many cars do you wish to catalog? ";
        cin >> c_num;
        cin.get();
    
        car * collect = new car [c_num];
    
        for (int i = 0; i < c_num; ++i) {
            cout << "Please enter the make: ";
            getline(cin, (collect + i)->production);
            cout << "Please enter the year made: ";
            cin >> ((collect + i)->proYear);
            cin.get();
    
        }
    
        cout << "Here is your collection: " << endl;
        for (int i = 0; i < c_num; ++i) {
            cout << (collect + i)->proYear << " " << (collect + i)->production << endl;
        }
        delete [] collect;
    
        return 0;
    }
    

    图片说明

    希望能帮到你!

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型