簡體   English   中英

如何編輯結構數組中的變量?

[英]How do I go about editing the variables in a struct array?

我已經用Google搜索了,問了我的同學,最后問了我的教授關於這個特殊問題的信息,但是我還沒有找到解決方案。 我希望這里有人可以幫助我。

基本上,我需要構建一個結構數組,每個結構包含4條信息:國家/地區名稱,國家/地區人口,國家/地區和國家/地區密度。 此信息將從.txt文檔寫入數組中的結構。 然后,該信息將從所述陣列寫入控制台。

不幸的是,在嘗試向數組中的結構寫入任何內容時,我遇到了2個錯誤。 “無法從'const char [8]'轉換為'char [30]'”,並且“沒有運算符'[]'與這些操作數匹配,操作數類型為:CountryStats [int]”。 這些錯誤均引用該行:

countries[0].countryName = "A";

請記住,我只是開始使用結構,這是我第一次在數組中使用它們。 另外,我必須使用數組,而不是向量。

這是我的代碼:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

struct CountryStats;
void initArray(CountryStats *countries);

const int MAXRECORDS = 100;
const int MAXNAMELENGTH = 30;

struct CountryStats
{
    char countryName[MAXNAMELENGTH];
    int population;
    int area;
    double density; 
};

// All code beneath this line has been giving me trouble. I need to easily edit the 
// struct variables and then read them.
int main(void)
{
    CountryStats countries[MAXRECORDS];
    initArray(*countries);
}

void initArray(CountryStats countries)
{
    countries[0].countryName = "A";
}

到目前為止,我只是試圖弄清楚如何將信息寫入數組中的結構,然后從中讀取信息到控制台。 在找到解決方案之后,其他所有內容都應該放到位。

哦,還有最后一點:我還沒有完全了解指針(*)的功能。 我對C ++還是比較陌生,因為我過去的編程教育主要是使用Java。 在尋求解決此問題的過程中,我的同學和教授對代碼中包含的所有指針都產生了影響。

提前致謝!

您沒有為以下定義定義:

void initArray(CountryStats *countries);

但對於:

void initArray(CountryStats countries);

在哪個countries不是數組。 由於沒有為CountryStats定義operator[] ,因此表達式CountryStats countries[0]無法編譯。

由於您不能使用std::vector (出於某些奇怪的原因),我建議您使用std::array

template<std::size_t N>
void initArray(std::array<CountryStats, N>& ref) {
    for (std::size_t i = 0; i < N; i++)
        // initialize ref[i]
}

當然,如果您感到受虐狂,也可以使用C樣式的數組:

void initArray(CountryStats* arr, int size) {
    for (int i = 0; i < size; i++)
        // initialize arr[i]
}

但是,您可能需要提供數組的維數作為第二個參數。

兩個問題

void initArray(CountryStats countries)

一定是:

void initArray(CountryStats *countries)

並且您必須使用strcpy復制c樣式字符串。 (但我建議使用c ++字符串代替char [])

strcpy(countries[0].countryName,"A");

但是我再說一遍,使用c ++功能,例如vector <>和string。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM