2017-11-03 6 views
2

나는 명령 행 프로그램을 만들고 있는데 문장의 다른 부분을 얻는 방법을 궁금해했다. 따라서 누군가가 cd Windows/Cursors을 입력했다면 if 문으로)는 cd을 입력 한 다음 (동일한 if 문에서) 나머지 문장을 선택하고이를 디렉토리로 설정합니다. 내 코드는문장에서 문장의 일부를 선택하는 방법 (C++)

#include "stdafx.h" 
#include <string> 
#include <iostream> 

using namespace std; 
int main() 
{ 
    while (1) 
    { 
     string directory = "C:/"; 
     string promptInput; 
     string afterPrint; 
     string prompt = "| " + directory + " |> "; 
     cout << prompt; 
     cin >> promptInput; 

     if (promptInput == "") 
     { 

     } 
     else if (promptInput == "h:/") 
     { 
      directory = "H:/"; 
     } 
     if (promptInput != "") { 
      cout << " " << afterPrint << "\n"; 
     } 
    } 
    return 0; 
} 

아직 시도하지 않았으므로 제안을드립니다.

도움을 주시면 대단히 감사하겠습니다.

-갈렙 심

+0

: 예를 들어, 비주얼 스튜디오, 그리고'#INCLUDE "에 stdafx.h"를 사용하는 경우 '이 제안, 파일의 첫 번째 일에'#INCLUDE "에 stdafx.h"를'했습니다. 그 위에있는 모든 것은 무시됩니다. 자세한 내용은 https://stackoverflow.com/questions/2976035/purpose-of-stdafx-h를 참조하십시오. 왜 사람들은이 smurf를 참아 : https://stackoverflow.com/questions/4726155/whats-the-use-for-stdafx-h-in-visual-studio – user4581301

답변

1

당신은 각 라인을 읽을 std::stringstream을 사용할 수 있으며 그것을 스트림으로 변환하십시오. 그런 다음 부분을 분리하여 줄을 끊고 줄의 첫 번째 단어를 기반으로 응답을 만듭니다. 관련없는

#include <sstream> 
... 
int main() 
{ 
    string line; 
    while(getline(cin, line)) 
    { 
     stringstream ss(line); 
     string cmd; 
     if(ss >> cmd) 
     { 
      if(cmd == "cd") 
      { 
       string dir; 
       if(ss >> dir) 
       { 
        cout << "changedir: " << dir << "\n"; 
       } 
      } 
      else if(cmd == "c:" || cmd == "c:\\") 
      { 
       cout << "changedir: " << cmd << "\n"; 
      } 
      else 
      { 
       cout << "error\n"; 
      } 
     } 
    } 
    return 0; 
} 
0

일반적인 대답은 당신의 문제 설정에 따라 다르지만로 볼 수 귀하의 예를 들어 특정 대답은 다음과 같습니다

else if (promptInput == "cd") 
{ 
    std::string directory; 
    std::getline(std::cin, directory); 
    ChangeDirectory(directory); 
}