2017-03-03 6 views
1

私が取り組んでいるプロジェクトの一部は、3Dプリンタに関する情報をテキストファイルに保存します。具体的には、それはすべき:の内容を依頼する前にファイルを作成する

  • チェック、それは必要なデータを、それが存在しない場合は
  • に移動し、存在して入力するユーザーに確認しない場合、ファイルが既に
  • が存在する場合

私の問題は、プログラムが最後のステップをスキップして、代わりに空のテキストファイルを作成し、ユーザーにデータを要求しないで移動するように思われることです。ここで問題を引き起こしているように見えるチャンクは次のとおりです。

int configCheck() { 

    if (std::ifstream(configName)) { 

     std::cout << "Configuration file already exists." << std::endl; 

    } 
    std::ofstream file(configName); 
    if (!file) { 

     std::cout << "Configuration file not found." << std::endl; 

     // ask for machine settings 

     std::cout << "Machine Configuration" << std::endl; 
     std::cout << "---------------------" << std::endl; 
     std::cout << "Machine Width (mm): "; 
     std::cin >> xLim; 
     std::cout << std::endl; 
     std::cout << "Machine Length (mm): "; 
     std::cin >> yLim; 
     std::cout << std::endl; 
     std::cout << "Machine Height (mm): "; 
     std::cin >> zLim; 
     std::cout << std::endl; 
     std::cout << "Nozzle Size (mm): "; 
     std::cin >> nozzleDia; 
     std::cout << std::endl; 
     std::cout << "Filament Size (mm) "; 
     std::cin >> filDia; 
     std::cout << std::endl; 

     // make and fill a configuration file 

     std::cout << "Creating configuration file..." << std::endl; 
     std::ofstream config; 
     config << xLim << std::endl; 
     config << yLim << std::endl; 
     config << zLim << std::endl; 
     config << nozzleDia << std::endl; 
     config << filDia << std::endl; 
     config.close(); 

    } 
} 

答えて

0

あなたは

std::ofstream file(configName); // Already creates the file if possible 
if (!file) { // ofstream state is good at that point and the whole 
      // code will be skipped 
} 

を観察されるようにはい、それは我々が重複としてあなたの質問をマークした後、私はあなたをリードしたいです

  • は、ファイルがexisかどうかをチェックするために小さなヘルパー関数を作成します。私はそこに見てきたbest possible solution用設定ファイルが

    if (!fileExists(configName)) { 
        std::ofstream file(configName); 
    } 
    
+0

が存在する場合、TS

bool fileExists(const char *fileName) { ifstream infile(fileName); return infile.good(); } 
  • を決定するためにそれを使用しての謝罪が重複 –

  • +0

    @CadeCyphersについて謝罪する必要はありませんです、ありがとうございました。重複したQ&Aは、本質的に悪いことではありません。すぐに研究が示されていないか、悪い例があります。有効な質問が重複している場合は、Stack Overflowで答えを調べるためのより良いネットワークをセットアップします。 –

    関連する問題