c++ - 来自输入的 C++ 文件,我找不到我的代码失败的地方
问题描述
我不明白为什么我的代码无法从键盘输入读取文件名,然后从该名称读取文件。我总是失败,有人可以帮助我并链接我一些有用的教程或指南吗?
#include <iostream>
#include <fstream>
#include <cstring>
#define LMAX 20
#define ERR1 -1
using namespace std;
int main()
{
ifstream infile;
char filename[LMAX];
cout << "Insert filename :" << '\n' << endl;
int i=0;
while (filename[LMAX]!= '\0')
{
cin >> filename[LMAX];
}
char* p1=nullptr;
p1=(char*) malloc (strlen(filename)*sizeof(char));
p1=&filename[LMAX];
infile.open("filename[LMAX]");
if(!infile.is_open())
{
cerr << "File not found!" << '\n' << endl;
return ERR1;
}
return 0;
}
解决方案
#include <iostream>
#include <fstream>
#include <cstring>
#define LMAX 20
#define ERR1 -1
using namespace std;
int main()
{
ifstream infile;
char filename[LMAX];
cout << "Insert filename :" << '\n' << endl;
// This is not the way to read a string
/*
int i=0;
while (filename[LMAX]!= '\0')
{
cin >> filename[LMAX];
}
*/
// Read your filename directly using cin
cin >> filename;
// This is an unused variable
/*
char* p1=nullptr;
p1=(char*) malloc (strlen(filename)*sizeof(char));
p1=&filename[LMAX];
*/
// Why are you passing the variable name as the filename?
/* infile.open("filename[LMAX]"); */
// Pass the actual filename
infile.open(filename);
if(!infile.is_open())
{
cerr << "File not found!" << '\n' << endl;
return ERR1;
}
return 0;
}
在旁边:
C++ 必须
std::string
使用字符串,那么为什么要坚持旧的 char 数组呢?cin >> filename
不会读取带空格的字符串。你可能想看看这个。
推荐阅读
- repl.it - 在本地使用 repl.it 数据库
- java - 我使用 BpNN 来拟合一些数据,但只能得到平均值
- c - C. 双向合并。计算比较
- flutter - 根据在 Flutter 中播放的歌曲获取图像
- assembly - 未知宏参数
- jwt - NextAuth 会话访问令牌错误
- verilog - 对于 verilog 上的加法器代码,如何将 1'b1 添加到 4 位向量 [3:0]A?
- python - 如何在 python tkinter 中从 txt 文件创建多个复选框
- python - Python3,jinja2,导入宏时出错
- powershell - 通过 WMI 查询获取帐户状态