2017-11-11 19 views
1

나는 C++을 배우므로 나와 함께 곰곰히 여겨서 멍청이를 미리 사과한다.getline()을 무한대로 사용하는 단어 C++ 프로그램 일치?

"command.txt"라는 파일의 각 줄에있는 첫 단어를 "num_lines", "num_words"또는 "num_chars"와 일치시키는 코드를 작성하려고합니다.

첫 번째 줄의 첫 번째 단어가 앞에서 언급 한 단어와 일치하지 않으면 다음 줄을 읽습니다. 일치하는 단어 (첫 번째 단어 만!)가 나오면 일치하는 단어가 인쇄됩니다. command.txt 파일의

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

using namespace std; 

ifstream comm_in("commands.txt"); // opens file 
string command_name = "hi"; // stores command from file 


bool is_command() { 
    if (command_name == "num_words" || command_name == "num_chars" || command_name == "num_lines") { 
     return true; 
    } else { 
     return false; 
    } 
} 


// FIND a first word of a line in file THAT MATCHES "num_words", "num_chars" or "num_lines" 
void get_command() { 

    string line; 
    char c; 

    while (!is_command()) { // if command_name does not match a command 

     // GET NEXT LINE OF FILE TO STRING 
     getline(comm_in, line); 

     // SUPPOSED TO GET THE FIRST WORD OF A STRING (CANT USE SSTREAM) 
     for (int i = 0; i < line.size(); i++) { // increment through line 
      c = line[i]; // assign c as index value of line 

      if (c == ' ' || c == '\t') { // if c is a space/tab 
       break; // end for loop 
      } else { 
       command_name += c; // concatenate c to command_name 
      } // if 
     } // for 
    } // while 
    return; 
} 

int main() { 

    get_command(); 
    cout << command_name; // supposed to print "num_lines" 
} 

내용 :

my bear is happy 
and that it 
great ha 
num_lines sigh 

내 터미널에서 실행할 때 제대로 컴파일하지만은 아무것도가 표시되지 않습니다 여기

내 모든 코드는 ; 그것은 로딩을 멈추지 않는 것 같습니다. 어떻게 해결할 수 있습니까?

+0

봐. 티가 멈추게하려면 어떻게 될까요? – Jay

+0

while 루프는 is_command가 true를 반환 할 때 중지됩니다. 즉 command_name == "num_lines"일 때 command.txt 파일의 네 번째 줄을 읽으면 중지해야합니다. 이 논리에 문제가 있습니까? – Salvatross

+0

그게 어떻게됩니까? 루프를 빠져 나가면 프로그램을 인쇄하고 종료해야합니다. – Jay

답변

0

뭔가 잘못되어 파일 끝에 도달하면 루프가 중단되지 않습니다. getline(comm_in, line)if(!getline(comm_in, line)) break;으로 변경하거나 더 나은 방법으로 루프의 조건으로 사용하십시오.

는 또한 각 패스 command_name을 재설정해야 :

while(getline(comm_in, line)) 
{ 
    command_name = ""; 
    for(int i = 0; i < line.size(); i++) 
    { 
     c = line[i]; 
     if(c == ' ' || c == '\t') 
      break; 
     else 
      command_name += c; 
    } 
    if(is_command()) 
     break; 
} 
1

당신은 정말 아침 (말하자면) 전역 변수를 사용하는 습관을 벗어나고 싶은 자신을 미워하지 않으려면 . get_command을 (최소한) 두 개의 함수 (특히 줄을 포함하는 문자열에서 첫 번째 단어를 가져 오는 함수)로 나누면 더 쉽게 삶을 찾을 수 있습니다.

좀 더 이런 식으로 코드를 작성하는 것 :

bool is_cmd(std::string const &s) { 
    return s == "num_words" || s == "num_chars" || s == "num_lines"; 
} 

std::string first_word(std::istream &is) { 
    std::string line, ret; 

    if (std::getline(is, line)) { 
     auto start = line.find_first_not_of(" \t"); 
     auto end = line.find_first_of(" \t", start); 
     ret = line.substr(start, end - start); 
    } 
    return ret; 
} 

void get_command(std::istream &is) { 
    std::string cmd; 

    while (!(cmd = first_word(is)).empty()) 
     if (is_cmd(cmd)) { 
      std::cout << cmd; 
      break; 
     } 
} 

이 아직 완벽하지 않습니다 (예를 들어, 잘못된 형식의 입력은 여전히 ​​장애를 일으킬 수 있습니다)하지만 적어도 내가 '무엇의 움직임이다 말하기가 더 좋은 방향입니다.

0
// FIND a first word of a line in file THAT MATCHES "num_words", "num_chars" or "num_lines" 
void get_command() 
{ 
    string line; 
    char c; 

    while (!is_command()) { // if command_name does not match a command 

     // GET NEXT LINE OF FILE TO STRING 
     if(getline(comm_in, line),comm_in.fail()){ 
      // end reading 
      break; 
     } 

     //clear 
     command_name = ""; 

     // SUPPOSED TO GET THE FIRST WORD OF A STRING (CANT USE SSTREAM) 
     for (int i = 0; i < line.size(); i++) { // increment through line 
      c = line[i]; // assign c as index value of line 

      if (c == ' ' || c == '\t') { // if c is a space/tab 
       break; // end for loop 
      } else { 
       command_name += c; // concatenate c to command_name 
      } // if 
     } // for 
    } // while 
    return; 
} 

이 문제의 핵심은 command_name을 지우지 않았기 때문입니다.

더 많은 것은 파일 끝에 도달했는지 여부에 대한 판사를 추가해야합니다.

PS : if(getline(comm_in, line),comm_in.fail())if(getline(comm_in, line)) 같다하여 'while` 루프가 무엇을하고 있는지에