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?

Anj Jo
  • 137
  • 2
  • 8

1 Answers1

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.

Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
  • This worked. BTW does this work for trailing whitespaces too? – Anj Jo Jul 26 '17 at 09:16
  • @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. – Blastfurnace Jul 26 '17 at 09:18
  • How can i use std::ws to trim trailing whitespace? – Anj Jo Jul 26 '17 at 09:22
  • @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. – Blastfurnace Jul 26 '17 at 09:26
  • @AnjJo This may help: [What's the best way to trim std::string?](https://stackoverflow.com/q/216823/445976) – Blastfurnace Jul 26 '17 at 09:29