2016-07-09 11 views
0

Weit davon entfernt, aber jetzt versuche ich, dieses Programm nach dem Dateinamen zu fragen und es in String zu speichern, dann zu ifstream konvertieren und dann prüfen, ob die Datei gültig ist, indem sie die Funktion isvalid aufruft, um sie zu überprüfen, und sie wird true zurückgeben, wenn sie gültig ist und false, wenn nicht und wenn sie gültig ist, wird die Hauptfunktion "Datei ist gültig" sein. Dann wird es so lange wiederholt, bis der Exit eingegeben wird. Aber jedes Mal kommt es falsch zurück und ich weiß nicht, was falsch ist. Ich werde großartig sein für jede Hilfe.Validierung der Datei in der Funktion und Aufruf in der Hauptdatei und Ausgabe "Datei ist gültig", wenn sie gültig ist

# include <iostream> 
#include <string> 
#include<fstream> 
using namespace std; 

bool isValid(ifstream& file) 
{ 
    if (file.good()) 
    { 

     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 



int main() 
{ 
    string file_name; 
    cout <<"please enter a HTML file name or hit 'exit' to quit and if you want to clear file please enter 'clear': "; 
    cin >> file_name; 
    ifstream my_file(file_name.c_str()); 



    while (file_name != "exit") 
    { 
     if ((isValid(my_file)) == true) 
     { 
      cout << "Hello" << endl; 
     } 
     string file_name; 
     cout <<"please enter a HTML file name or hit 'exit' to quit and if you want to clear file please enter 'clear': "; 
     cin >> file_name; 
     ifstream my_file(file_name.c_str()); 
    } 
} 

Antwort

0

Sie haben ein Problem namens "Shadowing".

int main() { 
    int i = 0; 
    while (i == 0) { 
     int i = 1; // declares a new variable that 
     // "shadows" (obscures) the outer i inside this scope 
    } // shadow i goes away, original i returns 
} 

Der obige Code wird für immer laufen, weil i im Rahmen der while-Schleife das ist i in Haupt erklärt.

Ihr Code tut dies:

int main() 
{ 
    // ... 
    ifstream my_file(file_name.c_str()); 

    while (file_name != "exit") 
    { 
     if ((isValid(my_file)) == true) // << outer my_file 
     // ... 
     ifstream my_file(file_name.c_str()); // << scope-local variable 
    } // << scope local my_file goes away 
} 

Sie könnten Ihren Code zu prüfen, Refactoring Doppelarbeit zu vermeiden und vereinfacht es:

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

int main() { 
    for (;;) { // infinite loop 
     std::string file_name; 
     std::cout <<"please enter a HTML file name or hit 'exit' to quit and if you want to clear file please enter 'clear': " << std::flush; 
     if (!std::getline(std::cin, file_name)) 
      break; 
     if (file_name == "exit") 
      break; 

     std::ifstream my_file(file_name); 
     if (!my_file.is_open()) { 
      std::cerr << "unable to open file " << file_name << '\n'; 
      continue; 
     } 

     std::cout << "hello\n"; 
    } 
} 

ich es als eine Übung, dich zu verlassen, wieder einzuführen Ihre isValid-Funktion.