簡體   English   中英

C ++奇怪的函數行為

[英]C++ strange function behavior

我最近一直在使用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;
}

我只是想檢查一個char是一個有效的空格或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 - 指向要分析的以null結尾的字節字符串的指針

雖然你傳入:

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

這些都不是以空字符結尾的字節字符串。 可以手動添加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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM