gpt4 book ai didi

c++ - 尝试在 C++ 中打开文件时出错

转载 作者:搜寻专家 更新时间:2023-10-31 00:29:45 24 4
gpt4 key购买 nike

我已经编写了一个 C++ 代码来在循环中创建一些文件名。例如,我将运行循环八次并创建 8 个文本文件,例如:

input0.txt, input1.txt,......., input7.txt

我的示例代码如下:

#include<iostream>
#include<cstdio>
#include<string.h>
#include<stdlib.h>
#include<fstream>
#include <sstream>
using namespace std;

std::string to_string(int i) {
std::stringstream s;
s << i;
return s.str();
}

int main()
{
FILE *fp;
int i=0;
string fileName;
string name1 = "input";
string name2 = ".txt";
while(i<=7)
{
fileName = name1+ to_string(i)+ name2;
cout<<fileName<<"\n";
fp=fopen(fileName,"r");
i++;
}

}

但是,当我运行代码时,出现以下错误:

 error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'FILE* fopen(const char*, const char*)'

代码有什么问题吗?解决方案是什么?

最佳答案

只需查看您收到的错误消息即可。

fopen() 采用 const char* 而不是 std::string 作为参数。要获取字符串的 const char*,请使用 .c_str() 函数。

fopen() 虽然是一个 c-api。作为替代方案,您还可以使用 C++ 的文件流。

std::fstream 用于读/写,std::ifstream 仅用于输入。 std::ofstream 仅用于输出。

关于c++ - 尝试在 C++ 中打开文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39699368/

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