C++ 动态结构数组用户输入

标签 c++

我正在尝试使用 Stephen Prata 的“C++ Primer Plus 第 6 版”自学 C++。第 5 章练习之一要求我设计一个包含许多汽车名称和年份的动态结构。所有这些信息都是由用户输入。 我的问题是:

1) 我可以在结构中使用字符串对象而不是 char 数组吗?如果是这样,你能告诉我怎么做吗?

2) 如何让用户输入包含多个单词的名称?我一直在尝试使用 get()、getline() 等,但我无法使它工作。

3) 我知道这是一个简单的程序,但可以通过哪些方式改进代码?

提前致谢。

#include<iostream>
using namespace std;

const int ArSize = 20;

struct automobile
{
    char name[ArSize];
    int year;
};

int main()
{
cout << "How many cars do you wish to catalogue?\n";
int number;
cin >> number;

automobile * car = new automobile[number];
int n = 0;

while (n < number)
{
    cout << "Car #" << n+1 << ":\n";
    cout << "Please enter the make: ";
    cin >> car[n].name; cout << endl;

    cout << "Please enter the year: ";
    cin >> car[n].year; cout << endl;
    n++;
}

    cout << "Here is your collection:\n";

int m = 0;
while (m < number)
{
    cout << car[m].year << " " << car[m].name << endl;
    m++;
}
delete [] car;
return 0;
}

最佳答案

1) Can I use a string object instead of an array of char in the structure? If so, could you tell me how?

是的,只需提供一个类型为std::string的成员变量:

struct automobile
{
    std::string name;
    int year;
};

2) How can I enable the user to input a name that consists of more than one word? I've been trying to use get(), getline() etc. but I just can't make it work.

使用std::getline() :

cout << "Please enter the make: ";
std::getline(std::cin,car[n].name); cout << endl;

3) I know it is a simple programme but in what way could the code be improved?

此类问题最好在 SE Code Review 提出,只要你有工作代码。对于 Stack Overflow,这通常简单地呈现为过于宽泛

关于C++ 动态结构数组用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36139673/

相关文章:

c++ - 关于构建 shell 时的 fork()

c++ - 通过 system() 调用启动另一个程序会阻塞套接字

c++ - gnuplot 可以绘制交互式图形项吗?

c++ - 用于 Metro 风格应用程序的 HTML/CSS 渲染器

c++ - 如何: variadic wrapper function that catches exceptions of input function

c++ - 如何将 std::dec/hex/oct 放入查找数组

c++ - 创建小部件的指南

c++ - 程序在函数重载中的工作

c++ - SDL - 滚动通过(屏幕外)表面

c++ - Linux 上缺少包含文件的编译器选项