【发布时间】:2017-10-10 22:47:57
【问题描述】:
我是 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”有一条红色波浪线,下拉菜单显示以下错误:
不存在从“
std::basic_istream<char, std::char_traits<char>>”到“bool”的合适转换函数
我不太明白错误信息,但我设法让这个程序正常工作:
一个简单的演员表:
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;
}
所以,我真正的问题是:
- 我的解决方案是否可行或有更好的方法?
- 为什么在您的教育材料上出现错误? 可以想象应该首先经过彻底的测试。或者这是 只是 Visual Studio (intelliSense) 特定的,但在 其他编译器?
【问题讨论】:
-
请以逐字文本而不是图片的形式发布错误消息!
-
只需使用
return someFile >> city >> rain;而不是这个多余的if() else构造。不需要static_cast。 -
谢谢。我实际上尝试了 return someFile >> city >> rain;首先,但仍然得到红色波浪。只有演员才能将其移除!
-
你可能想试试a more recent book。
-
离题 - 但我发现自己想知道为什么
readData需要ifstream而不是接受任何istream(如果您希望能够从 @ 阅读,那会更好987654335@ 或istringstream代替)。然后,正如其中一个答案所暗示的那样,我倾向于让它返回istream&而不是bool。
标签: c++ visual-studio-2017 intellisense