2016-12-24 105 views
-4

我正在創建一個程序,其中用戶輸入mcqs和選項,然後將數據保存到txt file.How我可以做到這一點,我試試,但它不工作。將數據保存到txt文件中? C++

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 
int main() 
{ 
    ofstream outputFile; 
    std::string fname; 
    cout<<"Enter file name"; 
    std::getline (std::cin,fname); 
    outputFile.open(fname+".txt"); 
    std::string name; 
    std::string mcqs; 
    int x; 
    cout<<"How many questions want \n"; 
    cin>>x; 

    for(int i=1;i<=x;i=i+1){ 
     cout<"Enter question "+i; 
     std::getline (std::cin,name); 
     outputFile << name << endl; 
     cout<<"Option A"; 
     std::getline (std::cin,mcqs); 
     outputFile << mcqs << endl; 
     cout<<"Option B"; 
     std::getline (std::cin,mcqs); 
     outputFile << mcqs << endl; 
     cout<<"Option C"; 
     std::getline (std::cin,mcqs); 
     outputFile << mcqs << endl; 
     cout<<"Option D"; 
     std::getline (std::cin,mcqs); 
     outputFile << mcqs << endl; 
    } 

    outputFile.close(); 
    cout << "Done!\n"; 
    getchar(); 
    return 0; 
} 

我想保存mcqs和選項txt file.Thanks

+0

解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –

+0

你的代碼格式也應該有一個嚴重的過度工作。 –

回答

0

你的問題是與CIN獲得問題編號。您可以使用get_line和stringstream來讀取數字。

#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <string> 
using namespace std; 
int main() 
{ 
    ofstream outputFile; 
    std::string fname; 
    std::string str; 
    stringstream ss; 
    int x; 

    cout<<"Enter file name:"; 
    std::getline (std::cin,fname); 
    outputFile.open(fname+".txt"); 

    cout<<"How many questions want \n"; 
    std::getline (std::cin,str); 
    ss << str; 
    ss >> x; 
    if (x == 0) 
     cout << "Invalid question number...!" << endl; 

    for(int i=1;i<=x;i=i+1){ 
      cout<<"Enter question " << i << ":"; 
      std::getline (std::cin,str); 
      outputFile << str << endl; 

      cout<<"Option A:"; 
      std::getline (std::cin,str); 
      outputFile << str << endl; 

      cout<<"Option B:"; 
      std::getline (std::cin,str); 
      outputFile << str << endl; 

      cout<<"Option C:"; 
      std::getline (std::cin,str); 
      outputFile << str << endl; 

      cout<<"Option D:"; 
      std::getline (std::cin,str); 
      outputFile << str << endl; 
    } 

    outputFile.close(); 
    cout << "Done!\n"; 
    getchar(); 
    return 0; 
}