[英]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[]
還是別的嗎?
計算機語言基於一般規則和遞歸規則。 只需嘗試進行實驗並以基本理解進行推斷,即可構建看似復雜的內容。 來到您要達到的目標:
如果使用現代編譯器,最好使用std::array
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.