2010-09-11 74 views
-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代替了原来的文件类型(即:.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):error C2228:'.txt'的左边必须有class/struct/union 1> type是'char [256]' (42):错误C2228:'.out'的左边必须有class/struct/union 1> type(文件名)是'char [256]'

回答

1

要改变文件扩展名:

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

尝试使用'x.y.z'之类的文件名或者像“abc.def \ xyz \ file.txt”这样的路径进行测试。 – 2010-09-11 22:53:08

+0

这应该是find_last_of,而不是find_first_of :)谢谢你指出我的错误。 – 2010-09-11 22:57:55

+0

谢谢!像魅力一样工作! – MSwezey 2010-09-12 18:58:00

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"); 
+0

我试过,但得到了一个错误。看着它,并且.open不会将字符串作为参数。但是我发现了一行代码。 inFile.open(inputFile.c_str(),ios :: in); outFile.open(outputFile.c_str(),ios :: in); – MSwezey 2010-09-12 18:56:24

0

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

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

是的,现在我认为这是完美的逻辑意义! – MSwezey 2010-09-12 18:58:29