【问题标题】:User input filename用户输入文件名
【发布时间】:2014-11-10 22:21:44
【问题描述】:
#include <iostream>
#include <fstream>
#include <cassert>
#include <cstring>

using namespace std;

const int WL = 20;
const int WR = 1000;

void READ (ifstream &, char[], char[][WL], int &);
void PRINT (char [][WL],  int, int,  int );

int main()
{
    ifstream file;
    string fileName;
    cout << "enter file name";
    getline(cin, fileName);
    char name[] = fileName;
    char Word[WR][WL];
    int row = 0;
    int WordMax;
    int WordMin;

    file.open(name);
    assert(! file.fail() );
    READ (file, name, Word, row);
    file.close();
    cout << "file successfully opened" << endl;

    cout << "word length: \n";
    cout << "min: ";
    cin >> WordMin;
    cout << "max: ";
    cin >> WordMax;

    PRINT(Word, row, WordMin, WordMax);

    system("pause");
    return 0;
}

据我了解,问题是我不能在char name[]中使用fileName,因为它是string,但是char name[]稍后会在代码中使用...我可以改成什么解决这个问题?

【问题讨论】:

    标签: c++ stdstring c-strings


    【解决方案1】:

    不要为此引入新变量name,只需使用c_str() method of std::string:

    string fileName;
    //...
    getline(cin, fileName);
    //...
    file.open(fileName.c_str());
    //...
    READ (file, fileName.c_str(), Word, row);
    

    【讨论】:

      【解决方案2】:

      您可以将字符串转换为字符一次,例如 filename.c_str()

      例如,char name[] = fileName.c_str();

      【讨论】:

      • 所以只需用 fileName.c_str() 替换字符串 fileName?因为它说它是未声明的,我该如何声明呢?
      • @Mastarg 我相信你必须#include &lt;string&gt; 或#include &lt;string.h&gt;
      • 方法std::string::c_str() 不应该需要除string 之外的任何其他标头。你是什​​么意思“它说它是未声明的”?
      • `fileName' 未声明(首先使用此函数)
      • 好吧,也许有办法改变“ char name[] = "filename"; " 以便用户输入那个文件名?
      【解决方案3】:

      首先,定义:char name[sizeof(fileName)]; 然后,您可以使用strcpy(name, fileName.c_str()); 应该可以,但您可能需要在将 fileName 值传递给 char 数组之前检查它来管理 null 情况。

      【讨论】:

      • sizeof(fileName) 与字符串的长度没有任何关系。此外,您无法在编译时确定用户字符串的长度。
      • 字符名[sizeof(fileName)]; cout
      • @Vortico: fileName.size() 代替?
      • @TimChristin 您仍然无法在编译时确定用户输入的大小。无法使用静态 char 数组处理所有可能的用户输入,因此您必须像 Rews Prog 的回答那样使用 char 指针(例如动态数组)。
      • 哇,这听起来太糟糕了!没有意识到这个限制......感谢Vortico的精确!希望帖子现在得到解决。
      猜你喜欢
      • 2022-01-05
      • 1970-01-01
      • 2016-08-29
      • 2013-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      相关资源
      最近更新 更多