繁体   English   中英

C ++中struct中的struct中的字符串

[英]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";

另一个提示是,我真的建议您学习研究方法,这个问题已被数百万次回答,并且答案遍及整个Internet。

这是我的建议:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM