我无法让这个字符串在C++中工作

I can not get this string to work in C++

本文关键字:C++ 工作 字符串      更新时间:2023-10-16

我不知道为什么我遇到字符串文件名的编译错误;它说它"超出范围"我尝试使用字符串但没有奏效,我从教科书中复制了一个基本的字符串示例代码,甚至没有编译。

#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;
}

在 C++ 11 之前,文件流仅采用const char*作为文件名。对于 C++ 11,std::string也有过载。如果没有重载,请在调用 open 中使用 filename.c_str() 来获取指向内容为 filename 的 C 字符串的指针。