gpt4 book ai didi

C++ 奇怪的函数行为

转载 作者:太空狗 更新时间:2023-10-29 23:35:38 24 4
gpt4 key购买 nike

我最近一直在使用 C++ 工作,并且只使用了该语言的一小部分(我将其称为带有类的 C),所以我一直在努力学习 C++ 的其他一些特性语言。为此,我打算编写一个简单的 JSON 解析器,但几乎立即遇到了我无法破译的障碍。这是代码:

//json.hpp
#include <cstring>


namespace JSON
{
const char WS[] = {0x20,0x09,0x0A,0x0D};
const char CONTROL[] = {0x5B,0x7B,0x5D,0x7D,0x3A,0x2C};

bool is_whitespace(char c) {
if (strchr(WS, c) != nullptr)
return true;
return false;
}

bool is_control_char(char c) {
if (strchr(CONTROL, c) != nullptr)
return true;
return false;
}
}

这是 main.cpp:

#include <iostream>
#include "json.hpp"

using namespace std;

int main(int argc, char **argv) {
for(int i=0; i < 127; i++) {
if(JSON::is_whitespace((char) i)) {
cout << (char) i << " is whitespace." << endl;
}
if(JSON::is_control_char((char) i)) {
cout << (char) i << " is a control char." << endl;
}
}
return 0;
}

我只是想检查一个字符是否是 JSON 中的有效空格或有效控制字符。

 is whitespace.
is a control char.
is whitespace.

is whitespace.
is whitespace.
is whitespace.
, is whitespace.
, is a control char.
: is whitespace.
: is a control char.
[ is whitespace.
[ is a control char.
] is whitespace.
] is a control char.
{ is whitespace.
{ is a control char.
} is whitespace.
} is a control char.

我已经看了好久了。我什至不知道在谷歌中输入什么搜索词来描述这个错误(或特征?)...任何解释将不胜感激。

最佳答案

如果您阅读了关于 strchr 的要求

const char* strchr( const char* str, int ch );

str - pointer to the null-terminated byte string to be analyzed

而你正在传递:

const char WS[] = {0x20,0x09,0x0A,0x0D};
const char CONTROL[] = {0x5B,0x7B,0x5D,0x7D,0x3A,0x2C};

它们都不是以 null 结尾的字节字符串。您可以手动添加一个 0:

const char WS[] = {0x20,0x09,0x0A,0x0D, 0x0};
const char CONTROL[] = {0x5B,0x7B,0x5D,0x7D,0x3A,0x2C, 0x0};

或者,更好的是,实际上不依赖于该行为:

template <size_t N>
bool contains(const char (&arr)[N], char c) {
return std::find(arr, arr+N, c) != (arr+N);
}

bool is_whitespace(char c) { return contains(WS, c); }
bool is_control_char(char c) { return contains(CONTROL, c); }

在 C++11 中:

template <size_t N>
bool contains(const char (&arr)[N], char c) {
return std::find(std::begin(arr), std::end(arr), c) !=
std::end(arr);
}

关于C++ 奇怪的函数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32512736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com