我正在嘗試讀取檔案內容并將其存盤在地圖資料結構中,我試圖跳過不包含在我的地圖中的評論部分。我無法按預期保持我的地圖,我有點不知道如何繼續。我已經提到了我的地圖應該是什么樣子。請建議我必須在代碼中添加哪些更改。感謝Advnc :)
輸入檔案:
# Filename: MyFile
# Revision: 107
Items Types count price
snacks junkfood
Mango fruit 5 50
strawbery fruit 10 50
carrot veggie
burger junkfood
beetroot veggie 4 20
cinnamon masala
預期的輸出檔案:存盤在map<string, string> [key] [value]
Items -> Types count price
snacks -> junkfood
Mango -> fruit 5 50
strawbery -> fruit 10 50
carrot -> veggie
burger -> junkfood
beetroot -> veggie 4 20
cinnamon -> masala
CPP 檔案:
#include <map>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
typedef std::pair<std::string, std::string> attribute_pair;
void check(ifstream &inputFile, map<string, string> &diffm)
{
diffm.clear();
std::string line;
while (getline(inputFile, line))
{
std::stringstream ss(line);
attribute_pair attribute;
while (ss >> attribute.first >> attribute.second)
{
if (attribute.first != "#")
diffm[attribute.first] = attribute.second;
}
}
}
int main(int argc, char const *argv[])
{
map<string, string> list1;
if (argc >= 2)
{
std::ifstream inputFile(argv[1]);
check(inputFile, list1);
map<string, string>::iterator itr;
for (itr = list1.begin(); itr != list1.end(); itr )
{
cout << itr->first << " " << itr->second << "\n";
}
}
else
{
std::cerr << "Usage <prog name here> <filename1 here> <filename2 here>\n";
return -2;
}
}
uj5u.com熱心網友回復:
我感覺很慷慨,我在某種程度上猜測您的要求(特別是地圖的價值部分應該如何)。我沒有測驗過這段代碼。
void check(ifstream &inputFile, map<string, string> &diffm)
{
diffm.clear();
std::string line;
while (getline(inputFile, line))
{
if (line.empty() || line[0] == '#')
{
// skip blank or comment lines
}
else
{
std::stringstream ss(line);
std::string key, value;
// read first string (key)
ss >> key;
// read rest of line (value)
getline(ss, value);
diffm[key] = value;
}
}
}
uj5u.com熱心網友回復:
這是個錯誤
while (getline(inputFile, line, '\0'))
應該
while (getline(inputFile, line))
第一個讀取由\0
字符終止的“行”,我嚴重懷疑這是你想要的。你想要由\n
字符終止的行,這就是第二個版本所做的。
這說明了 Beta 提出的觀點。您嘗試的第一件事是錯誤的,因此撰寫和測驗其余代碼是浪費時間。您應該撰寫一小段代碼(例如檢查您是否可以一次讀取一個檔案),并且只有當您確定它正在作業時,您才應該繼續執行其余的任務。例如,在弄清楚如何一次讀取一行檔案之后,下一個任務應該是看看您是否可以跳過注釋行。看?將任務分解成更小的任務并解決每個更小的任務,然后再進行下一個任務。這是至關重要的。解決不僅僅意味著撰寫和編譯代碼,還意味著撰寫代碼并撰寫一些代碼來檢查它是否正常作業(就像一些std::cout << ...
代碼一樣)。
始終邁出小步(尤其是在學習時)。一次撰寫 20 行代碼可能會出錯的地方太多了。撰寫兩行、三行或四行代碼,測驗該代碼,然后僅在它作業時再撰寫一些代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/496606.html
上一篇:MYSQL按重量匹配樣本
下一篇:多邊形和圓形演算法