gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:44:17 25 4
gpt4 key购买 nike

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

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