输出和输入的文件名的简单用户请求

时间:2010-09-11 22:18:47

标签: c++ filenames istream

如何请求用户输入我的程序需要读取的文件名,并让其输出带有.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'左边必须有class / struct / union   1 GT; type是'char [256]'

     

c:\ users \ matt \ documents \ visual studio 2008 \ projects \ dspi \ dspi \ dspi.cpp(42):错误C2228:'。out'左边必须有class / struct / union   1 GT; type是'char [256]'

3 个答案:

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

答案 1 :(得分:1)

更改fileName扩展名:

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

答案 2 :(得分:0)

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

inFile.open(fileName + ".txt");
outFile.open(fileName + ".out");
相关问题