我有這樣的代碼作為我的默認建構式。我試圖從我的檔案(census2020_data.txt)中正確讀取所有數值。該檔案包含字母和數字,由州和一個代表人口的值組成。資料檔案中的一個值有空格(它是多個字),這使得我的程式不能正確地從檔案中讀取。
我如何結合getline()函式來幫助從我的檔案中正確讀取?我將在下面附上填充內容作為例子。
構造器:
state_class::state_class()
{
//intially count, capacity, and pop_DB are initialized with following values:
count = 0;
capacity = 5;
ifstream in;
pop_DB = new population_record[capacity];
in.open("census2020_data.txt")。
//檢查檔案是否能被打開。
while (!in.eof()
{
if (Is_Full()
{
double_size()。
}
else; }
{
in >> pop_DB[count].state_name >> pop_DB[count].population;
count ;
}
}
in.close()。
}
census2020_data.txt:
阿拉斯加 710231
亞利桑那州 6392017
哥倫比亞特區 601723
阿肯色州 2915918
加州 37253956
康涅狄格州 3574097
特拉華州 897934
佛羅里達州 18801310
印第安納州 6483802
緬因州 1328361
俄勒岡州 3831074
賓夕法尼亞州 12702379
羅得島州 1052567
南卡羅來納州 4625364
馬里蘭州 5773552
馬薩諸塞州 6547629
密歇根州 9883640
科羅拉多州 5029196
明尼蘇達州 5303925
密西西比州 2967297
愛荷華州 3046355
堪薩斯州 2853118
肯塔基州 4339367
路易斯安那州 4533372
密蘇里州 5988927
蒙大拿州 989415
南達科他州 814180
田納西州 6346105
德克薩斯州 25145561
猶他州 2763885
佛蒙特州 625741
內布拉斯加 1826341
內華達州 2700551
新罕布什爾州 1316470
新澤西州 8791894
喬治亞州 9687653
夏威夷 1360301
愛達荷州 1567582
伊利諾伊州 12830632
新墨西哥州 2059179
紐約州 19378102
北卡羅來納州 9535483
北達科他州 672591
俄亥俄州 11536504
俄克拉荷馬州 3751351
弗吉尼亞州 8001024
華盛頓州 6724540
西弗吉尼亞州 1852994
威斯康星州 5686986
懷俄明州 563626
波多黎各 3725789
阿拉巴馬州 4779736
uj5u.com熱心網友回復:
operator>>在空白處停止讀取,這不是你在這種情況下需要的。
我建議使用std::getline()來讀取整行,然后使用std::string::rfind()來找到數字前的最后一個空格字符,然后使用std::string:substr()來將文本與數字分開。 例如:
state_class::state_class()
{
//intially count, capacity, and pop_DB are initialized with following values:
count = 0;
capacity = 5;
pop_DB = new population_record[capacity];
//check if file can be openedstd::ifstream in("census2020_data.txt")。
std::string line;
while (std::getline(in, line))
{
if (Is_Full()
double_size()。
auto pos = line.rfind(' ')。
pop_DB[count].state_name = line.substr(0, pos) 。
pop_DB[count].population = std::stoi(line.substr(pos 1))。
count;
}
這就是說,與其手動維護你自己的population_record[]陣列,不如考慮使用std::vector<population_record>代替。讓標準庫為你處理記憶體管理問題:
private:
std::vector<population_record> pop_DB;
state_class::state_class()
{
//檢查檔案是否能被打開。
std::ifstream in("census2020_data.txt")。
std::string line;
while (std::getline(in, line))
{
auto pos = line.rfind(' ') 。
population_record rec;
rec.state_name = line.substr(0, pos);
rec.population = std::stoi(line.substr(pos 1) )。)
pop_DB.push_back(rec)。
}
}
//根據需要使用pop_DB.size()和pop_DB[index]...。
我甚至建議實作operator>>,直接從ifstream讀取population_record條目:
std::istream& operator>>(std::istream& in, population_record & rec)
{
std::string line;
if (std::getline(in, line))
{
auto pos = line.rfind(' '/span>)。
rec.state_name = line.substr(0, pos) 。
rec.population = std::stoi(line.substr(pos 1) )。)
}
return in;
}
...
private:
std::vector<population_record> pop_DB;
state_class::state_class()
{
//檢查檔案是否能被打開。
std::ifstream in("census2020_data.txt")。
人口記錄rec;
while (in >> rec) {
pop_DB.push_back(rec)。
}
}
//根據需要使用 pop_DB.size() 和 pop_DB[index]...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/328097.html
標籤:
下一篇:對建構式的未定義參考問題
