cpp:处理字符串与数字的混合输入(动态数组)

c++中可以很方便的使用动态数组以及结构,也可以很方便的输入输出。不过,对于混合输入,特别是字符串与数字的混合输入的时候,还是需要一点注意。

对于c++中数组,以及结构的数组也要留意一下,当前的变量对应的是指针,还是对象,或者是值?

下面是一个简单的案例,收集用户的车子厂商,以及生产年份,并输出相关收集的内容。

#include <iostream>
#include <cstring>

using namespace std;
struct car {
    string company;
    int productiveYear;
};

int main() {

    int Amount;
    cout << "How many cars do you wish to catalog? ";
    cin >> Amount;
    cin.get(); // drop \n
    car *cars = new car[Amount];

    const int TempLength = 80;
    char *tempInput = new char[TempLength];
    for (int index = 0; index < Amount; ++index) {
        cout << "Car #" << (index + 1);

        cout << "Please enter the make:";
        cin.getline(tempInput, TempLength);
        cars[index].company = tempInput;

        cout << "Please enter the your made:";
        cin >> cars[index].productiveYear;
        cin.get(); // drop \n
//        cout << cars[index].company << "## " << tempInput;
    }
    delete[] tempInput;

    cout << "Here is your collection:" << endl;
    for (int i = 0; i < Amount; ++i) {
        cout << cars[i].productiveYear << " " << cars[i].company << endl;
    }
    return 0;
}

输出如下:(粗体是输入)

How many cars do you wish to catalog? 2
Car #1
Please enter the make:比亚迪 秦
Please enter the your made:1962
Car #2
Please enter the make:保时捷 卡宴
Please enter the your made:1866
Here is your collection:
1962 比亚迪 秦
1866 保时捷 卡宴

注意几点:

  • cars是一个数组;
  • cars[0]是一个结构体,还是一个结构指针呢?– 是结构体,不是指针。
    • 通过typeinfo头文件中的typeid(arg).name()可以证实这一点。
  • 混合输入的时候,注意换行时cin的不同处理。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值