【发布时间】:2016-10-06 19:06:23
【问题描述】:
我目前正在使用此代码接收标准输入并将其放入字符串中。然后使用分隔符标记化 #
std::string input;
std::getline(std::cin,input, '\0');
std::string delimiter = "#";
StringTokenizer strtok(input,delimiter);
这使得 getline 读取直到找到空字符(我认为)并将整个字符串传递给输入。当我运行 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 文件都以两个字符 ## 结尾。有没有一种方法可以在到达此字符串(?)时停止读取输入,而不是等待空字符?
【问题讨论】:
-
strtok()是最糟糕的选择。 -
添加与第一个不同字符的第二个分隔符?
-
为什么不传递文件名而只读取文件?!
-
@deW1 我需要接受标准输入,所以我不知道 txt 的名称是什么。它必须适用于任何标准输入。
-
你能更准确地说出你想要什么吗?