c++中字符串到字符的转换不正常
conversion string to character in c++ Not Working Properly
创建一个接收文件名的函数,但它不能正常工作,因为它接收到"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);
你应该像
那样正确地初始化Chrchar 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;
}
相关文章:
- Visual C++(VS2017)中用户定义的转换不明确
- C++中的memset函数工作不正常
- C++通常的算术转换不转换
- 字符类型转换不兼容
- 通用线程池类工作不正常
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 用户定义的转换不能在C++中使用static_cast
- curl_easy_perform() 失败:SSL 对等证书或 SSH 远程密钥不正常
- 名为DLL的C++windows服务程序工作不正常
- C++-循环中的If语句工作不正常
- While循环和if/else语句工作不正常
- Qthread ::更改系统时间时睡眠不正常
- 阵列中的元素不正常地变化
- C++:最大数组值函数工作不正常
- 为什么用户定义的转换不会在调用对象上隐式发生
- 为什么转换不起作用
- 为什么在相同大小的功能参数中隐式转换不会发出警告
- C++ 读取 UTF-8 文件正常,转换为 UTF-16 正常,写回文件不正常
- c++中字符串到字符的转换不正常
- 从char*到wchar*的转换不能正常工作