gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:46:15 24 4
gpt4 key购买 nike

我正在尝试使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com