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

标签 c++ ifstream

我有一个名为“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/

相关文章:

c++ - 在 C++11 中获取函数指针的语法

c++ - Fstream 正在耗尽我的生命

自定义类对象的 C++ vector - 复制构造函数已删除 - std::ifstream

C++ 无法检查函数内部的 ifstream/ofstream.is_open()

c++ - 生成文件 - C++11

c++ - 如何在 map 中同时打印键和值?

c++ - 想要在 istream C++ 的行尾读取重要的 double 值

c++ - 在 C++ 中扩展模板参数的名称

c++ - 在类里面使用模板