c ++:如何将原始字符串传递给像evaluate这样的函数(" 2 + 2 \ 0 + 2")?

时间:2016-04-06 11:17:38

标签: c++ string templates c++11 null

编辑:: std::string infix="2+2\0+2";如何将其传递给函数evaluate(std::string s){cout << s}? =&GT; 2 + 2 + 2?

EDIT2 :: \0NULL个字符;我检查语法的函数从字符串中读取每个字符,如果它与数字或运算符不同,则抛出异常。我想读取null字符并抛出异常,但evaluate("2+2\0+2")返回4

我在c ++ 11中编写了一个带有测试的简单计算器,支持中缀表示法。

我有一个函数int evaluate( const std::string & infix ),它根据我的字符串计算结果(即evaluate( "((-3+--4*-(-19+5)))" )返回53)。一切正常,直到......

当我创建一些测试时,我可以写ASSERT_EQ(6, evaluate("2+2+2"))。但是当我写ASSERT_EQ(6, evaluate("2+2\0+2")时,一切都会出错(这应该抛出一个exception,但它会返回4)。

那么如何将一个字符数组传递给一个函数,不知道它的大小并且在其中有空字符?当const char cstr[] = "2+\0+2"; evaluate(cstr);未发送完整数组时:(

3 个答案:

答案 0 :(得分:3)

问题不在于功能方面,而在于呼叫方。要从包含空字节的字符串文字构造std::string,您需要使用其中一个重载来获取有关字符串大小的信息。

一个这样的重载(number 4 here)接受char指针和大小。由于字符串文字是char数组,因此您可以使用函数模板检索它们的大小:

template <std::size_t N>
std::string make_string(char const (&lit)[N]) {
    return {lit, N};
}

......并使用它:

ASSERT_EQ(6, evaluate(make_string("2+2\0+2")));

您也可以使用相同的原则直接通过重载函数来处理字符串文字:

template <std::size_t N>
auto evaluate(char const (&lit)[N]) {
    return evaluate({lit, N});
}

答案 1 :(得分:0)

  

当const char cstr [] =“2 + / 0 + 2”时;评价(CSTR);不发送完整数组:(

您可以使用std::string的use构造函数来接受迭代器范围,例如:

// Using macro
#define ARR_TO_STR(a) std::string(std::cbegin(a), std::cend(a))

// And template function
template <typename T, size_t N>
std::string ArrToStr( T (&t)[N] ) {
    return std::string(std::cbegin(t), std::cend(t));
}

int main()
{
   ASSERT_EQ(6, evaluate(ArrToStr("2+\0+2")))
}

答案 2 :(得分:0)

我的猜测是你没有尝试测试“2加2 null_byte加2”,而是你试图测试“2加2除以零加2”。

如果是这样,请记住在C ++字符串文字中,您需要输入一个双反斜杠(因为反斜杠用作许多不可打字字符的转义字符)。

尝试

ASSERT_EQ(6, evaluate(R"2+2\0+2"))

或者,因为您使用的是C ++ 11

String encodeImage(Bitmap bitmap) {

        BitmapFactory.Options options = null;
        options = new BitmapFactory.Options();
        options.inSampleSize = 3;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        // Must compress the Image to reduce image size to make upload
        // easy
        try {

            bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
        } catch (Exception e1) {
            // TODO Auto-generated catch block

        }

        System.out.println("SIZE OF BITMAP " + sizeOf(bitmap));

        byte[] byte_arr = stream.toByteArray();
        // Encode Image to String

        try {
            encodedString = Base64.encodeToString(byte_arr, 0);
        } catch (Exception e) {
            // TODO Auto-generated catch block
        }


        return encodedString;

    }

使用“原始”字符串文字