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
.