나는 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
내 터미널에서 실행할 때 제대로 컴파일하지만은 아무것도가 표시되지 않습니다 여기
내 모든 코드는 ; 그것은 로딩을 멈추지 않는 것 같습니다. 어떻게 해결할 수 있습니까?
봐. 티가 멈추게하려면 어떻게 될까요? – Jay
while 루프는 is_command가 true를 반환 할 때 중지됩니다. 즉 command_name == "num_lines"일 때 command.txt 파일의 네 번째 줄을 읽으면 중지해야합니다. 이 논리에 문제가 있습니까? – Salvatross
그게 어떻게됩니까? 루프를 빠져 나가면 프로그램을 인쇄하고 종료해야합니다. – Jay