【问题标题】:C++ Files from input, I can't find where my code fails来自输入的 C++ 文件,我找不到我的代码失败的地方
【发布时间】:2020-07-16 12:47:18
【问题描述】:

我不明白为什么我的代码无法从键盘输入读取文件名,然后从该名称读取文件。我总是失败,有人可以帮助我并链接我一些有用的教程或指南吗?

#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++ string file


    【解决方案1】:
    #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 &gt;&gt; filename 不会读取带有空格的字符串。你可能想看看this

    【讨论】:

    • 那么是否允许以这种方式插入少于LMAX个字符的字符串?我试图找到一种方法让我的代码这样做
    • @AvengerScarlet 是的,它可以。你试图做的实际上是一个无限循环。
    • 我知道可以使用 ,但是对于这个练习,我的教授希望我们避免使用新的 C++ 函数和库,我们使用的是混合代码。
    • @AvengerScarlet 没问题,这就是我在 Aside 部分提到它的原因。更正后的代码可以正常工作。
    • 复制并粘贴到我的 IDE (Clion) 中,它工作正常
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    相关资源
    最近更新 更多