2

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++;
        }
    }
}

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

Output

 name1 with spaces
n

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

3
  • 1
    Instead of skipping the white-space, why not trim the string after reading? Commented Jul 26, 2017 at 9:06
  • But we will have to write a trim function by ourselves, right? Commented Jul 26, 2017 at 9:13
  • Yes, but it's easy and there are many examples all over the 'net (including quite a few here on SO). Commented Jul 26, 2017 at 9:13

1 Answer 1

7

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);

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

Sign up to request clarification or add additional context in comments.

5 Comments

This worked. BTW does this work for trailing whitespaces too?
@AnjJo Are you talking about your getline call? Unfortunately getline reads the entire line until the default delimiter (a newline) or EOF. If there are trailing spaces you'll need to trim them.
How can i use std::ws to trim trailing whitespace?
@AnjJo In combination with getline? You can't, that reads everything up to but not including the newline. You'll need to use some string trimming code (search here on SO). std::ws is most useful in discarding whitespace left from a previous stream extraction (>>) operation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.