【发布时间】:2017-04-08 19:19:51
【问题描述】:
int main(){
std::cout << "Insert file name / or path. \n NOTE: ONLY INPUTS. DELETES PREVIOUS DATA.\nV.6" << std::endl;
std::string filen;
std::cin >> filen;
std::ofstream myFile;
try{
myFile.open(filen, std::ios::out);
}
catch(std::fstream::failure){
std::cout << "Could not open file!\n Make sure the name and data type are valid.";
system("pause");
}
while(true){
int press = getch();
if(press == 43) myFile.close();
if(press == 8){myFile << "\b" << " " << "\b";std::cout << "\b" << " " << "\b" << std::flush;}
if(press == 13){ myFile << "\n"; std::cout << "\n" << std::flush;}
if(press != 43 && press != 127 && press != 13 && press != 8){myFile << (char)press;std::cout << (char)press;}
}
return 0;
}
每当我选择一个文本文件并按退格键时,我会检查文档,当我检查文本文档时,我会得到如下随机字符:
【问题讨论】:
-
题外话:您需要为流打开例外。默认情况下,流不会抛出。一般来说,没有输入错误会更好,因为输入错误太常见了,不能被认为是异常的。您可以通过测试对象
if (!myFile)将进入if的主体来测试流操作是否成功,如果流报告了错误。如果您认为无论如何都需要例外,请阅读以下内容:en.cppreference.com/w/cpp/io/basic_ios/exceptions