首页 > 解决方案 > 来自输入的 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;
}

标签: c++stringfile

解决方案


#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;
}

在旁边:

  1. C++ 必须std::string使用字符串,那么为什么要坚持旧的 char 数组呢?

  2. cin >> filename不会读取带空格的字符串。你可能想看看这个


推荐阅读