iStream 重载 - 从文件中读取字符串
istream overloading -reading string from file
我正在尝试从文件中读取Person对象列表,将这些对象输出到内存流中。如果我不必从文件中读取,我能够让它工作,我可以手动输入每个对象值并且它工作正常,但我正在努力从文件中提取的行作为输入到 istream>>重载运算符
从文件中读取
string str
while (getline(inFile, str))
{
cout << "line" << str << endl; // I am getting each line
cin >> people // if I manually enter each parameter of object it works fine
str >> people // ?? - doesnt work - how do i pipe??
}
Person.cpp
// operator overloading for in operator
istream& operator>> (istream &in, People &y)
{
in >> y.firstName;
in >> y.lastName;
in >> y.ageYears;
in >> y.heightInches;
in >> y.weightPounds;
return in;
}
class People
{
string firstName;
string lastName;
int ageYears;
double heightInches;
double weightPounds;
// stream operator
friend ostream& operator<< (ostream &out, People&);
friend istream& operator>> (istream &in, People&);
};
假设你有一个字符串std::string str
。您希望对该字符串使用格式化提取。但是,std::string
不是std::istream
。毕竟,它只是一个简单的字符串。
相反,您需要一个与字符串内容相同的istream
。这可以通过std::istringstream
来完成:
std::istringstream in(str);
in >> people;
相关文章:
- 如何使用Luacneneneba API正确读取字符串和表参数
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 读取字符串文本输入以创建 2D 矢量
- 罗马数字到阿拉伯语 (vinculum) - 读取字符串中的字符
- C++:从文件中读取字符串和整数,并获得最大数字
- C++,从文件中读取字符串,分段错误
- 如果语句错误地读取字符串,则始终在第一个条件返回
- 如何从内存中读取字符串?
- 如何创建一个C++程序来读取字符串数组中的信息,然后将其排序到类中?
- 我需要C++读取字符串数组中每个单词的第一个字母
- 读取字符串C++的字符时出错
- 读取字符串直到标志 (C++)
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++输入文件流无法从文件中读取字符串
- 读取字符串字符时出错
- 如何读取<字符串,矢量<对<int,字符串的映射>>>
- 如何使此函数使用 getline 读取字符串并使用 int 执行相同的行为?
- C++ 使用 Strtok 读取字符串字符时出错
- 使用 getline 读取字符串,但每行中都有换行符