我无法理解为什么我的程序没有输出。 有人可以指出我忽略的规则吗?如您所见,我读取了一个类中的文件,并通过公开继承的子类访问相同类的打印函数。
#include <string>
#include <iostream>
#include <fstream>
class mainClass
{
public:
void print();
void read();
std::ifstream dataFile;
protected:
double first, second;
std::string mainString;
bool truth;
};
void mainClass::read()
{
dataFile.open("data.txt");
}
void mainClass::print()
{
while (dataFile >> mainString >> first >> second >> truth)
{
std::cout << mainString << first << second << truth;
}
}
int main()
{
mainClass instance;
instance.read();
instance.print();
return 0;
}
数据.txt:
Pie 3.14515 69 true
Apple 4.234 42 true
Potato 5 4.532 false
Carrot 55 1.2204 true
Corn 7.53221 12 false
最佳答案
您的读取运算符 dataFile >> mainString >> first >> second >> truth
总是失败,因为它无法读取 bool 值“true/false”。如果您想将 bool 值作为文本读取,您应该使用 std::boolalpha
修饰符
dataFile >> mainString >> first >> second >> std::boolalpha >> truth;
关于c++ - ifstream 变量循环不打印任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36684934/