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

来源:互联网 发布:工商局可以投诉淘宝吗 编辑:程序博客网 时间:2024/05/29 12:52

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 0
原创粉丝点击