C++中结构中结构中的字符串
String in struct in struct in C++
所以我必须做另一个练习。这一次,我需要定义一个结构和一个100元素的数组,它将存储有关书籍的信息(标题、作者、ID号、价格),以及一个简单的函数,它将打印有关存储的所有书籍的信息。我从这个代码开始:
#include <iostream>
using namespace std;
int main()
{
struct name_surname {string name, surname;};
struct book {string title; name_surname author_name, author_surname; int ID; int price;};
return 0;
}
现在呢?如何将其存储在数组中?
您只需创建一个类型为book或name_surname的数组或任何您想要的数组。
示例:
book arr[100];
arr[0].title = "The last robot";
arr[0].ID = 2753;
提示:
如果结构/类以大写字母开头,这是一种很好的编程实践,因此更容易区分它们,也更容易将变量命名为不带大写字母的相同名称。实例
struct Name_surname
{
string name, surname;
};
Name_surname name_surname[100];
name_surname[0].name = "MyName";
另一个建议是,我真的建议你学会如何研究,这个问题已经被回答了数百万次,答案遍布互联网。
这是我的建议:
struct book
{
string title;
string name_surname;
string author_name;
string author_surname;
int ID;
int price;
};
struct Database
{
book *array;
void printDatabase()
{
for(int i = 0 ; i < 100 ;i++)
cout<<array[i].title<<endl;
}
Database()
{
array = new string [100];
}
};
您的名称结构似乎有点混乱,但创建数组只是声明一个变量,并在其后面附加[]
以给出大小。
例如:
struct full_name
{
std::string firstname;
std::string surname;
};
struct book
{
std::string title;
full_name author;
int ID;
int price;
};
int main()
{
// Declare an array using []
book books[100]; // 100 book objects
// access elements of the array using [n]
// where n = 0 - 99
books[0].ID = 1;
books[0].title = "Learn To Program In 21 years";
books[0].author.firstname = "Idont";
books[0].author.surname = "Getoutalot";
}
你怎么看:
#include <iostream>
using namespace std;
struct book {string title; string name; int ID; int price;} tab[100];
void input(book[]);
void print(book[]);
int main()
{
input(tab);
print (tab);
return 0;
}
void input(book tab[])
{
for (int i=0;i<3;i++)
{
cout<<"nBook number: "<<i+1<<endl;
cout<<"title: ";cin>>tab[i].title;
cout<<"name: ";cin>>tab[i].name;
cout<<"ID: ";cin>>tab[i].ID;
cout<<"price: ";cin>>tab[i].price;
}
}
void print (book tab[])
{
for (int i=0; i<3; i++)
{
cout<<"nBook number: "<<i+1<<endl;
cout<<"title: "<<tab[i].title;
cout<<"nname: "<<tab[i].name;
cout<<"nID: "<<tab[i].ID;
cout<<"nprice: n"<<tab[i].price;
}
}
我在一些Yt视频的帮助下做到了这一点。它是有效的,但是,有没有办法做得更好,或者顺其自然?我有一个问题:为什么这些函数参数?我不能说tab[]
或其他什么吗?
计算机语言基于通用和递归规则。试着用基本的理解来进行实验和推断,构建看似复杂的东西。实现您想要实现的目标:
- 我们知道,数组可以为任何数据类型(基元或派生的,可以称之为POD和ADT)声明
- 我们知道,struct可以由任意数据类型的任意数量的元素组成
- 现在,我们可以看到,说MyStruct[]和说int[]一样自然
如果使用现代编译器,最好选择std::array
。
相关文章:
- C++结构到字符串
- 从字符串中获取结构的大小
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 如何解析表示树状数据结构的字符串
- 如何将字符串与结构(也包括字符串)进行比较?
- 如果结构中的字符串比使用的 p/调用签名长或短,会发生什么情况?
- 在向量 C++14(无限制联合)的结构内的联合中创建和存储字符串
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 将字符串存储在 constexpr 结构中
- 为什么我的结构在包含字符串时崩溃?
- 如何将字符串字符与结构数组进行比较?
- 无法使用 strcpy 将字符串复制到静态结构成员
- c++ 将函数参数(带有模板变量的结构)转换为函数体内的字符串
- 在 c++ 中使用字符串变量选择静态类结构,而不带对象
- 如何输出属于向量数组的结构字符串
- 为什么我不能像正常一样初始化 typedef 结构字符串或字符?
- 如何引用结构字符串成员
- c++运算符+=重载结构字符串
- 如何将平面列表合并转换为层次结构字符串
- 如何在c++中比较两个结构字符串