C++ : 如何在使用 getline() 和 ifstream 对象从文件中读取一行时跳过第一个空格?
C++ : How to skip first whitespace while using getline() with ifstream object to read a line from a file?
我有一个名为"items.dat"的文件,在订单itemID,itemPrice和itemName中包含以下内容。
item0001 500.00 item1 name1 with spaces
item0002 500.00 item2 name2 with spaces
item0003 500.00 item3 name3 with spaces
我编写了以下代码来读取数据并将其存储在结构中。
#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(( 在读取项目名称以及内容时读取开头的空格。
输出
name1 with spaces
n
我想跳过开头的空格。我该怎么做?
std::ws
IO 操纵器可用于丢弃前导空格。
一种紧凑的使用方法是:
getline(fileRead >> std::ws, tmpItem[i].name);
这会在将ifstream
中的任何空格传递给getline
之前丢弃它。
相关文章:
- 需要从存档中读取一行文本.txt直到找到"hhh",然后转到下一行
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- 使用std::getline()读取一行
- C++ : 如何在使用 getline() 和 ifstream 对象从文件中读取一行时跳过第一个空格?
- 如何从文本文件中读取一行并将其分为不同的变量
- 使用 getline 从输入文件读取一行到输出文件
- 如何在文本文件中仅读取一行,该文本文件使用QT具有特定单词
- 无法弄清楚为什么只从文件中读取一行矩阵以及为什么我无法将 2D 数组传递给函数
- 如何从文件中读取一行中的特定字符
- c++从ifstream中读取一行的最后一个变量
- 无法从文件中读取一行的所有整数(ifstream)
- 从文件中读取一行并将其放入字符串中(使用 fstream)
- 从.txt文件中读取一行,然后插入变量
- 从文件中读取一行,并在其中搜索字符串(c++)
- 在c++中读取一行.txt文件的一部分
- 我无法使用 getline() 读取一行
- std::getline只读取一行:
- 启动 QProcess 并一次读取一行输出
- C++以int形式读取一行字符串
- 在C++中读取一行之后的行不起作用