当使用getchar时输入特定字符串时如何打破循环?



考虑以下代码:

#include <iostream>
int main() {
int c;
while ((c = getchar()) != EOF) {
if (c == 't') {
std::cout << '\';
std::cout << 't';
}
if (c == 'b') {
std::cout << '\';
std::cout << 'b';
}
if (c == '\') {
std::cout << '\';
std::cout << '\';
}
if (c == "break") {
exit(c);
} else {
std::cout << c;
}
}
return 0;
}

众所周知,char只有1个字节。因此,如果我想执行c == "break", IDE会抛出这样的错误:error: ISO forbids comparison between pointer and integer [-fmprermissive].

但是如果我将双引号改为单引号,IDE会发出警告:warning: character constant too long for its type. And the consequence of this is the whole code malfunctions.

结论

我如何添加字节char让代码成功运行?

您可以做的是使用std::vector来存储输入缓冲区,然后比较它。
解决方案如下:

#include <vector>
#include <iostream>
int main()
{
std::vector<char> input;
std::string breakString = "break";
int c;
while ((c = getchar()) != EOF)
{
// check if our input vector length is greater than the break string length
if (input.size() >= breakString.size())
{
// get the last characters in the input buffer
std::string lastInput(input.data() + input.size() - breakString.size(), breakString.size());
// compare it with the break string
if (lastInput == breakString)
{
break;
}
}
input.push_back(static_cast<char>(c));
}
return 0;
}

相关内容

  • 没有找到相关文章