Anj Jo Anj Jo - 3 years ago 240
C++ Question

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

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download