-1

如何要求用户输入我的程序需要读取的文件名并让它输出带有.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 ]'

4

3 回答 3

1

您正在使用 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");
于 2010-09-11T22:25:14.183 回答
1

要更改文件扩展名:

string fileName;
cin >> fileName;
string newFileName = fileName.substr(0, fileName.find_last_of('.')) + ".out";
于 2010-09-11T22:30:12.517 回答
0

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

inFile.open(fileName + ".txt");
outFile.open(fileName + ".out");
于 2010-09-11T22:27:01.370 回答