我正在学习c++,所以请多多包涵,并对任何愚蠢的行为表示歉意。
我正在尝试编写一些代码,以将名为“command.txt”的文件中每行的第一个单词与“num_lines”,“num_words”或“num_chars”相匹配。
如果第一行的第一个单词与前面提到的单词不匹配,它将读取下一行。
一旦碰到匹配的单词(仅第一个单词!),它将打印出匹配的单词。
这是我所有的代码:
#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
它可以正确编译,但是当我在终端中运行它时,什么也没有显示。它似乎从未停止加载。
我怎样才能解决这个问题?
最佳答案
如果出现问题,并且到达文件末尾,循环将永远不会停止。您应该将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;
}
关于c++ - 使用getline()无限运行来匹配Word C++程序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47233935/