[英]Having trouble reading items from a file (C++)
因此,我在獲取文本文件中的最后一項以讀取字符串對象時遇到麻煩。
我已經創建了一個名為“ Car”的類,並且應該從文件中讀取“ Car”對象的所有參數,但不會注冊最后一個。
ifstream對象是“數據”
變量是:
string carType;
string reportingMark;
int carNumber;
string kind;
bool loaded;
string destination;
文本文件中的行顯示為:
汽車CN 819481保養假無
這就是我現在所擁有的:
getline(data, ignore); // ignores the header line
data >> carType >> reportingMark >> carNumber >> kind >> loaded;
while (data.peek() == ' ') // this and the next lines were the suggestions of the teacher to bypass the spaces (of which there are more than it will display here)
data.get();
getline(data, destination);
因此,它將讀取“目標”部分以外的所有內容。
該代碼似乎是正確的。 除了我不認為需要把
而(data.peek()=='')data.get();
getline(數據,目的地);
部分以讀取目的地。 相反,您可以簡單地將其讀取為數據>>目標。 此外,請檢查一下以確保輸入文件正確打開
if(data.isOpen()){// cout something}
我希望這有幫助! :)
檢查所有IO操作的返回值總是好的。 如果添加錯誤檢查,則可能能夠找到問題並找到解決方案。
if (!getline(data, ignore)) // ignores the header line
{
std::cerr << "Unable to read the header\n";
exit(EXIT_FAILURE);
}
if ( !(data >> carType >> reportingMark >> carNumber >> kind >> loaded))
{
std::cerr << "Unable to read the data\n";
exit(EXIT_FAILURE);
}
while (data.peek() == ' ') // this and the next lines were the suggestions of the teacher to bypass the spaces (of which there are more than it will display here)
data.get();
if ( !getline(data, destination) )
{
std::cerr << "Unable to read the rest of the line\n";
exit(EXIT_FAILURE);
}
怎么樣給“ ifstream”對象一個while循環,像這樣
ifstream ifstreamObject;
ifstreamObject.open("car.txt");
cout << "carType"<< ' '<< "reportingMark" << ' '<< "carNumber" <<' '<< "kind" <<' '<< "loaded"<<' '<<"destination"<< endl;
while(ifstreamObject >> carType >> reportingMark >> carNumber >> kind >> loaded >> destination )
{ cout <<"---------------------------------------------------------------------------"<<endl;
cout << carType<< ' '<< reportingMark << ' '<< carNumber <<' '<< kind <<' '<< loaded<<' '<<destination<< endl;
}
問題是這部分:
data >> carType >> reportingMark >> carNumber >> kind >> loaded;
在這里,您嘗試修改從流loaded
的布爾變量。 您希望讀取false
可以,但是不可以。 它僅接受0
或1
。
取而代之的是,不讀取布爾變量將切換流的err
位,這將導致讀取失敗后的所有其他內容。
要進行檢查,如果在該行之后立即執行data.peek()
,則將收到-1
,表示沒有有效的輸入。
要解決此問題,您將需要更改存儲信息的方式以存儲0/1
而不是true/false
,或者更好:
在讀取數據之前,先執行: data << boolalpha
。 這將使流將true/false
解釋為0/1
。
如果我是你,我將嘗試使用strtok函數從文件中讀取。
如果需要,可以閱讀以獲取更多信息strtok函數
我最近完成了此任務,我使用了strtok,因為它允許將文件的每一行拆分為單詞列表。 此外,它還可以避免分配空格等標點符號(因此,我發現它非常有用)
我的例子:我想從文件中讀取一些字符數據,例如種族,職業,生命值,攻擊和防御。
我文件的每一行看起來都像這樣:Human / soldier / 15/7/7
因此,我定義了一個存儲strtok函數返回值的char指針和一個存儲讀取的單詞的char指針,直到找到您之前考慮過的定界符。 (在此示例中:“ /”)
char* position = strtok(file, '/');
char* character_info = new char[size];
因此,您將該行存儲在character_info中,並在每次迭代中檢查位置值,直到完成讀取文件為止。
while(position != NULL){
// store position value
// call again strtok
}
希望對您有所幫助! =)
干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.