C++ : 如何在使用 getline() 和 ifstream 对象从文件中读取一行时跳过第一个空格?

C++ : How to skip first whitespace while using getline() with ifstream object to read a line from a file?

本文关键字:读取 一行 空格 第一个 文件 对象 C++ ifstream getline      更新时间:2023-10-16

我有一个名为"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::wsIO 操纵器可用于丢弃前导空格。

一种紧凑的使用方法是:

getline(fileRead >> std::ws, tmpItem[i].name);

这会在将ifstream中的任何空格传递给getline之前丢弃它。