gpt4 book ai didi

c++ - 在 C++ 中将字符串转换为字符无法正常工作

转载 作者:行者123 更新时间:2023-11-28 06:03:11 24 4
gpt4 key购买 nike

创建一个接收文件名但无法正常工作的函数,因为它接收到“Doc​​tor.txtG”但我给出“Doctor.txt”我该如何解决它?我的代码如下......

#include <iostream>
#include <conio.h>
#include <fstream>
using namespace std;

int number_of_lines = 0;

int numberoflines(string A);
int main()
{
cout<<numberoflines("Doctor.txt");

getch();
return 0;
}

int numberoflines(string A)
{
int Len;
char Chr[Len];

Len=A.length();
A.copy(Chr, Len);

//cout<<Len;
cout<<Chr;

string line;
ifstream myfile(Chr);
if(myfile.is_open())
{
while(!myfile.eof())
{
getline(myfile,line);
number_of_lines++;
}
myfile.close();
}
return number_of_lines;
}

最佳答案

它需要复制一个空终止字节到Chr。
使用

strcpy(Chr, A.c_str());

代替 A.copy(Chr, Len);

你应该像这样正确地初始化 Chr

char Chr[1024] 

char* Chr = new char[Len + 1].

关于c++ - 在 C++ 中将字符串转换为字符无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32884342/

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