c++ - ifstream 变量循环不打印任何内容

标签 c++ ifstream cout

我无法理解为什么我的程序没有输出。 有人可以指出我忽略的规则吗?如您所见,我读取了一个类中的文件,并通过公开继承的子类访问相同类的打印函数。

#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/

相关文章:

c++ - ifstream 没有返回正确的 int 值

c++ - 从文件中读取插入值到整数和字符 C++

c++ - 为什么 VC++ 允许 char 中有 2 个字符?

c++ - 为什么从 write() 调用 __kernel_vsyscall() 永远不会返回?

c++ - 构造函数不调用c++

c++ - 使用 boost::asio::basic_stream_socket::async_read_some 而不是 boost::asio::async_read 是否更有效?

c++ - const char* 有什么异常(exception)吗?

c++:ifstream删除文件的内容?

c++ - 混合 cout 和 printf 以获得更快的输出

c++ - 跨进程 PostMessage、UIPI 限制和 UIAccess=”true”