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

标签 c++ string file

我不明白为什么我会遇到字符串文件名的编译错误;它说它“超出范围”我尝试使用 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;
}

最佳答案

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

关于c++ - 我无法让这个字符串在 C++ 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35582808/

相关文章:

c - 如何创建头文件和文件处理

c++ - 在 C++ 中用 cin 读取同一行中的多个整数

c++ - A类在C类中不可见,但在main中可见。为什么?

c++ - Minifilter 驱动程序不阻止文件编辑

c - 将一个字符追加到列表中 n 次

java - 在长 java 字符串中查找行号和列号

c++ - 从对象列表中提取特定成员的优雅方式

python - 两个单词列表的概率分布

windows - 如何使用 Go 在 Windows 上获取文件所有者?

c++ - 转换 SRTM 数据时的负高度