C ++:如何在将getline()与ifstream对象一起使用时从文件中读取一行,如何跳过第一个空格? [英] C++ : How to skip first whitespace while using getline() with ifstream object to read a line from a file?

查看:392
本文介绍了C ++:如何在将getline()与ifstream对象一起使用时从文件中读取一行,如何跳过第一个空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为"items.dat"的文件,该文件在itemID,itemPrice和itemName顺序中具有以下内容.

I have a file named "items.dat" with following contents in the order itemID, itemPrice and itemName.

item0001 500.00 item1 name1 with spaces
item0002 500.00 item2 name2 with spaces
item0003 500.00 item3 name3 with spaces

我编写了以下代码来读取数据并将其存储在结构中.

I wrote the following code to read the data and store it in a struct.

#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()在读取项目名称和内容的同时读取开头的空白.

What I notice is the getline() reads the white space at the beginning while reading item name along with the content.

输出

 name1 with spaces
n

我想在一开始就跳过空格.我该怎么办?

I want to skip the whitespace at the beginning. How can I do that?

推荐答案

> c0> IO机械手可用于丢弃前导空白.

The std::ws IO manipulator can be used to discard leading whitespace.

一种紧凑的使用方式是:

A compact way to use it is:

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

这会在将ifstream传递给getline之前丢弃所有空白.

This discards any whitespace from the ifstream before it's passed to getline.

这篇关于C ++:如何在将getline()与ifstream对象一起使用时从文件中读取一行,如何跳过第一个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆