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'主體來測試流操作的成功。如果你認爲你想要例外,請閱讀:http://en.cppreference.com/w/cpp/io/basic_ios/exceptions – user4581301