c++中字符串到字符的转换不正常

conversion string to character in c++ Not Working Properly

本文关键字:转换 不正常 字符 字符串 c++      更新时间:2023-10-16

创建一个接收文件名的函数,但它不能正常工作,因为它接收到"Doctor "。但我给"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;
}

需要将一个以null结尾的字节复制到Chr中。
使用

strcpy(Chr, A.c_str());

代替A.copy(Chr, Len);

你应该像

那样正确地初始化Chr
char Chr[1024] 

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

您的问题正在发生,因为您正在尝试创建大小为Len的字符数组。但是在使用Len之前还没有初始化它。这就是为什么它会导致未定义的行为并产生这个问题。总是在声明变量时尝试初始化它们。否则,这个问题会经常发生。

但是,您不需要创建另一个字符数组。只需在ifstream的构造函数的参数中使用std::string::c_str();。我在下面给出一个示例代码。这应该能解决你的问题。

#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)
{
    string line;
    ifstream myfile(A.c_str());
    if(myfile.is_open())
    {
        while(!myfile.eof())
        {
            getline(myfile,line);
            number_of_lines++;
        }
        myfile.close();
    }
    return number_of_lines;
}