[英]C++ : How to skip first whitespace while using getline() with ifstream object to read a line from a file?
我有一個名為“ items.dat”的文件,該文件在itemID,itemPrice和itemName順序中具有以下內容。
item0001 500.00 item1 name1 with spaces
item0002 500.00 item2 name2 with spaces
item0003 500.00 item3 name3 with spaces
我編寫了以下代碼來讀取數據並將其存儲在結構中。
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
using namespace std;
struct item {
string name;
string code;
double price;
};
item items[10];
void initializeItem(item tmpItem[], string dataFile);
int main() {
initializeItem(items, "items.dat");
cout << items[0].name << endl;
cout << items[0].name.at(1) << endl;
return 0;
}
void initializeItem(item tmpItem[], string dataFile) {
ifstream fileRead(dataFile);
if (!fileRead) {
cout << "ERROR: Could not read file " << dataFile << endl;
}
else {
int i = 0;
while (fileRead >> tmpItem[i].code) {
fileRead >> tmpItem[i].price;
getline(fileRead, tmpItem[i].name);
i++;
}
}
}
我注意到的是,getline()會在讀取項目名稱和內容的同時讀取開頭的空白。
輸出量
name1 with spaces
n
我想在一開始就跳過空白。 我怎樣才能做到這一點?
可以使用std::ws
IO機械手丟棄前導空格。
一種緊湊的使用方式是:
getline(fileRead >> std::ws, tmpItem[i].name);
這將在ifstream
傳遞給getline
之前丟棄任何ifspace的空格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.