2015-11-08 56 views
-2

我是C++的新手。我寫了一個小程序來打開一個文件並用用戶的輸入寫入它。我需要修改這個程序,以便如果用戶輸入像'X'這樣的字符,程序應該關閉輸入窗口並退出程序。我不知道我該怎麼做。 我寫的代碼如下終止寫入操作並關閉C++中的文件

#include <iostream> 
#include <fstream> 
#include <string> 

using std::cout; 
using std::cin; 
using std::endl; 

int main() 
{ 
    std::ofstream outputFile; 
    outputFile.open("C:\\UseCr\\pp\\qt_projects\\test.txt"); 
    string sInput; 
    cout << "Please Enter the Text "; 
    outputFile << sInput << endl; 
    std::ifstream outputFile; 
    output.close(); 
    return 0; 
} 
+0

你想從'stdin'輸入?我很困惑你的投入應該來自哪裏。 – erip

+0

如果你不知道,堆棧溢出可能不是正確的地方。尋找初學者的論壇。 – Meier

回答

0

我可能會建議是這樣的:

#include <iostream> 
#include <fstream> 
#include <string> 

using std::cout; 
using std::cin; 
using std::endl; 
using std::string; 

int main() { 
    std::ofstream outputFile(filename); // This will open and close your file. Look up RAII 

    string sInput; 
    cout << "Please Enter the Text "; 
    std::getline(cin, sInput); // Get a string from stdin, strip newline. 
    // Check if it's a quit condition 
    if(sInput == "x" || sInput == "X") { 
     cout << "Entered 'x', now exiting." << endl; 
     qApp->quit(); // or something similar 
    } 
    // If it's not a quit condition, write to file 
    outputFile << sInput << endl; 
    // Once outputFile goes out of scope, it is closed. 
    return 0; 
} 
0
int main(){ 

     string sInput; 
     std::ofstream outputfile; 
     outputFile.open("C:\\UseCr\\pp\\qt_projects\\test.txt"); 
     cout << "Please enter the text : "<<endl; 

     do{ 
      getline(cin,sInput); //it read from the keyboard what the user write and save into sInput variable 
      outputfile << sInput<< endl; 
     }while(sInput!= "X" || sInput != "x"); 
     outputFile.close(); 
     } 
return 0; 
} 

`

+0

編譯while條件時有錯誤指示,因爲sInput是一個字符串,條件是Character。 – harian