我有一个名为“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
之前丢弃所有空格。
关于C++ : How to skip first whitespace while using getline() with ifstream object to read a line from a file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45322228/