读取输入,直到找到特定的字符串C ++

时间:2016-10-06 19:06:23

标签: c++ linux string

我目前正在使用此代码接收标准输入并将其放在字符串中。然后使用分隔符#

进行标记
std::string input;
std::getline(std::cin,input, '\0');
std::string delimiter = "#";
StringTokenizer strtok(input,delimiter);

这使得getline读取直到找到null字符(我认为)并将整个字符串传递给input.This在我运行cmd时在windows中工作正常并写下:

myprogram.exe 0 <testme.txt

我得到了我期待的输出。我遇到的问题是当我尝试在linux终端中运行类似命令时(a.out是我的程序)

./a.out < testme.txt 

在我按下ctrl-z之前,它不会停止寻找键盘输入。当我在我编写程序的IDE Code :: blocks中运行时也会出现这种情况。 Code :: blocks和linux都使用g ++编译,没有错误或警告。我认为我的问题在于等待空字符。使用空字符的原因是因为我的输入在多行上,当我刚使用getline(std :: cin,input)时,只读取了第一行。

示例testme.txt

 A B C D E F #
 A -> Bab #
 B -> C #
 ##

我正在使用我的代码

的示例
std::string data;
std::getline(std::cin,data, '\0');
std::string delimiter = "#";
StringTokenizer strtok(data,delimiter);
// places first token in tk1
std::string t1      = strtok.nextToken();
std::string tk1(t1);
// places next token in tk2
std::string t2      = strtok.nextToken();
std::string tk2(t2);
if(checkstring(tk2,"a") > 0) // this function checks the amount of "a"s in the token. I only care if there is at least 1 "a" so that is what the if statements are for.
    {
      a = a + 1;
    }
// do this if statement for every letter
// example: token = A -> abbbababababa then will print out a = 1 and b = 1

如果通过我的程序,testme.txt应该让我的程序输出:

 A B C D E F
 a= 1
 b= 1

我的问题

我的每个testme.txt文件都以两个字符##结尾。有没有办法可以在达到此字符串(?)时停止读取输入而不是等待空字符?

1 个答案:

答案 0 :(得分:1)

do{
//do stuff
if (yourString == "##")
    break;
}while(yourString != NULL);

有时比看起来更容易

编辑
你所有的#&#39;#&#39;没有用,如果你删除它们:

std::vector<std::string> tokens; // Storing all tokens
std::string line;
while (std::getline(file, line))
    tokens.push_back(line);

for (std::string s : tokens) //Gets all tokens one by one
    for (char c : s)// Gets all char in each token
        if (islower(c))// Checks if thats a lowercase letter
            std::cout << c << std::endl;

如果您想保留&#39;#&#39;:

while (std::getline(file, line))
    if (!line.find("#"));
        tokens.push_back(line);

如果您使用std :: cin而不是文件:

std::string input, line;
std::cin >> input;
std::stringstream sinput(input);

while (std::getline(sinput, line, '#'))
    tokens.push_back(line);
相关问题