gpt4 book ai didi

c++ - 书中的示例无法编译,将 ifstream 转换为 bool

转载 作者:可可西里 更新时间:2023-11-01 17:11:17 26 4
gpt4 key购买 nike

我是 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;
}

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

Chicago 3.70
Tampa 6.49
Houston 3.80

问题在于“bool readData”函数中的这一行:

bool foundData = someFile >> city >> rain;

我正在使用 Visual Studio Community 2017。“someFile”出现红色波浪线,下拉菜单显示以下错误:

no suitable conversion function from "std::basic_istream<char, std::char_traits<char>>" to "bool" exists

我不是很理解错误信息,但已经设法让这个程序与:

一个简单的转换:

bool readData(ifstream &someFile, string &city, double &rain)
{
return static_cast<bool>(someFile >> city >> rain);
}

或者这个作为替代:

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

所以,我真正的问题是:

  • 我的解决方案是否可行或是否有更好的方法?
  • 为什么在您创建的教育 Material 上会出现错误可以想象应该首先进行彻底测试。或者是这个只是特定于 Visual Studio (intelliSense),但在其他编译器?

最佳答案

我会考虑

  • 返回 std::ios&将上下文转换推迟到 bool

    std::ios& readData(std::ifstream &someFile, std::string &city, double &rain) {
    return someFile >> city >> rain;
    }

    结果是您可以直接使用它:

    if (readData(file, city, rain)) {
    // ...
    }

    接口(interface)将通过只包含 #include <iosfwd> 进行编译


  • 手动触发上下文转换:

    bool readData(std::ifstream &someFile, std::string &city, double &rain) {
    return bool{someFile >> city >> rain};
    }

关于c++ - 书中的示例无法编译,将 ifstream 转换为 bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46677148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com