我无法弄清楚为什么我要用字符串文件名编译错误;它说它“超出范围”我尝试使用cstrings但是没有用,我从教科书中复制了一个基本的字符串示例代码,甚至没有编译。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ifstream file1;
// setting variables up for calculation
string filename;
float average, x;
float total = 0;
float count = 0;
float min = 0;
float max = 0;
//asking for file name
cout << "What is the name of the file you wish to open" << endl;
getline(cin, filename);
// opening file
file1.open(filename);
if (file1.fail())
{
cout << "Failure to open that file, please try again." << endl;
return 0;
}
//reading file
if (file1.is_open())
{
while (file1 >> x)
{
if (x <= min)
{ x = min;
}
if (x >= max)
{ x = max;
}
total = total + x;
count++;
if (file1.eof())
{ break;
}
}
}
// final calculations and testing
average = (total / average);
cout << "Minimum = " << min << endl;
cout << "Maximmum = " << max << endl;
cout << "The total count = " << count << endl;
file1.close();
return 0;
}
答案 0 :(得分:2)
在C ++ 11之前,文件流仅将const char*
作为文件名。对于C ++ 11,std::string
也存在重载。如果您没有重载,请在调用filename.c_str()
时使用open
来获取指向内容为filename
的C字符串的指针。