2014-09-11 2 views
-1

나는 command1이나 command2와 같은 파일 이름과 함께 사용자 명령을 사용하는 프로그램을 작성 중이다. 지금은 파일에 대한 명령을 사용한 후에 더 이상 다른 파일에서 사용할 수 없기 때문에 루핑 구조에 문제가 있다고 생각합니다.두 개의 파일을 읽을 수 없습니까?

예 :

command1 example.txt 
... works... 
command1 anotherexample.txt 
wrong command! try again! 

언제든지 파일에서 명령이 작동하도록 코드를 수정할 수 있습니까? 나는 그것이 코드를 구조화하는 방식과 관련이 있다는 것을 알고 있지만, 나는 그것을 고칠 수 없다. 대신 CIN의

while (getline(cin, str1)){ 

    if (str1 == "bye") 
    { 
     return 0; 

    } else { 
     s1.str (str1); 
     s1 >> command; 
     s1 >> filename; 
     ifs.open(filename.c_str()); 

     if (ifs.fail()) {              
      cerr << "ERROR: Failed to open file " << filename << endl; 
      ifs.clear(); 

     } else { 

      if (str1 == "command1 " + filename) { 
       command1(filename); 

      } else if (str1 == "command2 " + filename) { 
       command2(filename);                 

      } else { 
       cout << "Wrong command! try again!" << endl; 
      } 
     } 
     ifs.close(); 
    } 
} 
return 0; 
+0

옆 경우 대답은 같은 게시물에 체크 표시를 클릭하는 것을 잊지 마세요 – Jay

+0

prompt()가 호출 되었기 때문에'ifs.close()'가 호출되지 않습니다. – Abhi

+0

각 메서드에서 ifs.close()를 시도했지만 작동하지 않았습니다. –

답변

0

주에 전달 된 인수를하고 파일 이름으로 사용하십시오 ifsteam

#include <fstream> 


int main(int argc, char** argv){ 
    // you may have a type problem just convert it into the correct type 

    std::ifstream file(argv[1]); 
    while (getline(file, str1)){ 
관련 문제