我正在学习C++,所以请耐心等待,并且事前为任何白痴道歉。匹配使用getline()无限运行的单词C++程序?
我试图写一些代码,将每行上的第一个字匹配到“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"
}
的command.txt文件的内容:
my bear is happy
and that it
great ha
num_lines sigh
编译正确,但是当我在终端运行它,什么也不显示;它似乎永远不会停止加载。 我该如何解决这个问题?
看看你的'while'循环做。什么会导致ti停止? – Jay
while循环在is_command返回true时停止,即当command_name ==“num_lines”时,它一旦读取到command.txt文件的第4行就必须停止?这个逻辑有什么问题吗? – Salvatross
这是怎么回事?一旦退出循环,它应该打印并退出程序。 – Jay