【问题标题】:Simple user request for filename for output and input用于输出和输入的文件名的简单用户请求
【发布时间】:2010-09-11 22:18:46
【问题描述】:

如何要求用户输入我的程序需要读取的文件名,并让它输出带有.out扩展名的名称?

例子:

char fileName[256];
cout << "What is the file name that should be processed?";
cin >> fileName;

inFile.open(fileName);
outFile.open(fileName);

但我需要将文件保存为 filename.out 而不是原始文档类型 (IE:.txt)

我试过了:

char fileName[256];
cout << "What is the file name that should be processed?";
cin >> fileName;

inFile.open(fileName.txt);
outFile.open(fileName.out);

但我收到以下错误:

c:\users\matt\documents\visual studio 2008\projects\dspi\dspi\dspi.cpp(41) : 错误 C2228: '.txt' 的左边必须有类/结构/联合 1> 类型是'char [256]'

c:\users\matt\documents\visual studio 2008\projects\dspi\dspi\dspi.cpp(42) : 错误 C2228: '.out' 的左边必须有类/结构/联合 1> 类型是'char [256]'

【问题讨论】:

    标签: c++ filenames istream


    【解决方案1】:

    更改文件扩展名:

    string fileName;
    cin >> fileName;
    string newFileName = fileName.substr(0, fileName.find_last_of('.')) + ".out";
    

    【讨论】:

    • 尝试使用类似“x.y.z”的文件名或类似“abc.def\xyz\file.txt”的路径进行测试。
    • 那应该是 find_last_of,而不是 find_first_of :) 感谢您指出我的错误。
    【解决方案2】:

    您正在使用 iostreams,暗示使用 C++。这反过来意味着您可能应该使用 std::string,它具有用于字符串连接的重载运算符 - 以及自动内存管理和增加安全性的良好副作用。

    #include <string>
    // ...
    // ...
    std::string input_filename;
    std::cout << "What is the file name that should be processed?\n";
    std::cin >> input_filename;
    // ...
    infile.open(input_filename + ".txt");
    

    【讨论】:

    • 我试过了,但出错了。查了一下,.open 没有将字符串作为参数。但我找到了一行代码,可以做到这一点。 inFile.open(inputFile.c_str(), ios::in); outFile.open(outputFile.c_str(), ios::in);
    【解决方案3】:

    filename.txt 意味着fileName 是一个对象,并且您想要访问它的数据成员.txt。 (类似的论点适用于fileName.out)。相反,使用

    inFile.open(fileName + ".txt");
    outFile.open(fileName + ".out");
    

    【讨论】:

    • 是的,现在我想想这完全合乎逻辑!
    猜你喜欢
    • 2015-10-04
    • 2016-08-16
    • 2013-12-24
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 2013-10-20
    相关资源
    最近更新 更多