C++ : How to skip first whitespace while using getline() with ifstream object to read a line from a file? -
i have file named "items.dat" following contents in order itemid, itemprice , itemname.
item0001 500.00 item1 name1 spaces item0002 500.00 item2 name2 spaces item0003 500.00 item3 name3 spaces i wrote following code read data , store in 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: not read file " << datafile << endl; } else { int = 0; while (fileread >> tmpitem[i].code) { fileread >> tmpitem[i].price; getline(fileread, tmpitem[i].name); i++; } } } what notice getline() reads white space @ beginning while reading item name along content.
output
name1 spaces n i want skip whitespace @ beginning. how can that?
the std::ws io manipulator can used discard leading whitespace.
a compact way use is:
getline(fileread >> std::ws, tmpitem[i].name); this discards whitespace ifstream before it's passed getline.
Comments
Post a Comment