本书未能编译,将ifstream转换为bool的示例

Web*_*er1 8 c++ intellisense visual-studio-2017

我是C++的学生.我正在阅读"从C++早期对象开始(第9版)"一书.第6章(关于函数)的示例27从文件中读取数据但不会编译.以下是完整代码:

// Program 6-27
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;

// Function prototype
bool readData(ifstream &someFile, string &city, double &rain);

int main()
{
    ifstream inputFile;
    string city;
    double inchesOfRain;

    // Display table headings
    cout << "July Rainfall Totals for Selected Cities \n\n";
    cout << " City      Inches \n";
    cout << "_________________ \n";

    // Open the data file
    inputFile.open("rainfall.dat");
    if (inputFile.fail())
    cout << "Error opening data file.\n";
    else
    {
        // Call the readData function
        // Execute the loop as long as it found and read data
        while (readData(inputFile, city, inchesOfRain) == true)
        {
            cout << setw(11) << left << city;
            cout << fixed << showpoint << setprecision(2)
                << inchesOfRain << endl;
        }
        inputFile.close();
    }
    return 0;
}

bool readData(ifstream &someFile, string &city, double &rain)
{
    bool foundData = someFile >> city >> rain;
    return foundData;
}
Run Code Online (Sandbox Code Playgroud)

这是数据文件Rainfall.dat的附带数据:

Chicago 3.70
Tampa 6.49
Houston 3.80
Run Code Online (Sandbox Code Playgroud)

问题出在"bool readData"函数中的这一行:

bool foundData = someFile >> city >> rain;
Run Code Online (Sandbox Code Playgroud)

我正在使用2017年的Visual Studio社区."someFile"获得一条红色波浪线,下拉列表显示以下错误:

从" std::basic_istream<char, std::char_traits<char>>"到" bool"不存在合适的转换函数

我真的不明白错误信息,但设法让这个程序使用:

一个简单的演员:

bool readData(ifstream &someFile, string &city, double &rain)
{
    return static_cast<bool>(someFile >> city >> rain);
}
Run Code Online (Sandbox Code Playgroud)

或者作为替代方案:

bool readData(ifstream &someFile, string &city, double &rain)
{
    if(someFile >> city >> rain)
        return true;
    else
        return false;
}
Run Code Online (Sandbox Code Playgroud)

所以,我真正的问题是:

  • 我的解决方案是否正常或有更好的方法吗?
  • 为什么教育材料上会出现错误,你可以想象应该首先对其进行全面测试.或者这只是Visual Studio(intelliSense)特定的,但在其他编译器上工作正常吗?

seh*_*ehe 8

我考虑一下



Bo *_*son 5

该流有一个成员

explicit operator bool() const;
Run Code Online (Sandbox Code Playgroud)

这使得它可以转换为一个bool值,但因为运算符explicit只适用于需要 bool 的上下文.

您已经发现这包括if语句和显式转换.它不包括其他类型的表达式,如赋值.

最初(C++ 98)运算符不是explicit(因为这些东西还没有发明)所以代码示例可能在当时有效.好像这本书中没有更新过这本书.