[英]Reading in both strings and ints from a text file c++
好,這是一筆交易。 下面是我文件的輸入。
3332453:Ryan:77 Easy Street
3324532:Tom:1 Victory Lane
3326854:Gary:69 Sexual Ave
3304357:Susan:11 Straight Road
3343651:Frank:96 Backwards street
我想做的是讀入數字,然后是名稱,然后是地址,並將它們存儲到BST
。 檢查完所有內容后,我認為我的插入程序工作正常。 它將名稱和地址正確插入每個位置,但key1保持為0或-955472。 以上所有數字均假定為7位數字(電話號碼)。 以下是我到目前為止可能會進行的最接近的嘗試。 我不是在要求別人給我代碼(盡管這樣做會有所幫助),而是向我解釋為什么我的實現不起作用以及如何改進它。 謝謝。
ifstream dataFile;
dataFile.open ("/Users/revaes12/Desktop/BinarySearch/BinarySearch/phone.dat.rtf");
for (int counter = 0; counter < 5; counter++)
{
getline(dataFile, tmp, ':');
person[counter].key1 = atoi(tmp.c_str());
getline(dataFile, person[counter].name1,':');
getline(dataFile, person[counter].address1);
PNTree.insert(person[counter].key1, person[counter]);
}
dataFile.close();
insert
調用的原型是“ template <class KeyType, class DataType> bool BST<KeyType, DataType>::insert (KeyType key, DataType data)
”。 另外,我知道atoi是C而不是C ++,但是我也嘗試了stringstream,但是也失敗了! 請幫忙!
在嘗試對您的問題進行逆向工程之后,我認為PNTree.insert
是錯誤的。 假設PNTree
是std::map<int, person_type>
,則該方法的insert
方法不使用這些類型的兩個參數。 下面是三個插入成員。
pair<iterator,bool> insert (const value_type& val);
iterator insert (iterator position, const value_type& val);
template <class InputIterator>
void insert (InputIterator first, InputIterator last);
並且value_type
是std::pair<int, person_type>
。 我想您想第一個插入一個node ,在這種情況下,最簡單的事情是:
PNTree[person[counter].key1] = person[counter];
還要注意,其中一些“數字”不能轉換為int
,它們只是大。 您必須使用long long
或std::string
來保存它們。
如果我要編寫此代碼,它將看起來像這樣 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.