C++中结构中结构中的字符串

String in struct in struct in C++

本文关键字:结构 字符串 C++      更新时间:2023-10-16

所以我必须做另一个练习。这一次,我需要定义一个结构和一个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