用户输入文件名

时间:2014-11-10 22:21:44

标签: c++ stdstring c-strings

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

据我了解,问题是我无法在fileName中使用char name[],因为它是string,但char name[]将用于{{1}}代码以后......我可以改变什么来解决这个问题?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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

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

答案 2 :(得分:-2)

首先,定义:char name[sizeof(fileName)]; 然后,您可以使用strcpy(name, fileName.c_str()); 应该可以工作但你可能需要通过检查fileName值来管理null case,然后再将它传递给char数组。