1

**更新

我试图了解 XCode 如何/为什么似乎在我的 C++ 源代码中添加了一个奇怪的字符,而实际上它正在删除它我正在创建一个简单的类并在学习 C++ 课程时使用 CATCH2 测试框架。我有一个将数字转换为单词的 numwords 类。

using namespace std;
//int main( int argc, char ** argv )
TEST_CASE("Numwords example", "[numwords]")
{
    bw::numword nw;
    uint64_t n;

    n = 3; REQUIRE( string(nw.words(n)) == "three");
    n = 47; REQUIRE( string(nw.words(n)) == "forty-seven");
    SUCCEED();
}

它失败了:

/Users/c.craig/Training/CPP/Working/Working/numword-test.cpp:21: FAILED:
  REQUIRE( string(nw.words(n)) == "forty-seven" )
with expansion:
  "forty-seven" == "forty-seven"

然后我通过仔细地将预期值复制/粘贴回我的测试中发现确实存在一些不可见的差异。就在那时,它开始神奇地过去了。我查看了我的 git diff 并看到了这个:

diff --git a/Working/numword-test.cpp b/Working/numword-test.cpp
index c8f58db..3643c03 100755
--- a/Working/numword-test.cpp
+++ b/Working/numword-test.cpp
@@ -18,5 +18,5 @@ TEST_CASE("Numwords example", "[numwords]")
     uint64_t n;

     n = 3; REQUIRE( string(nw.words(n)) == "three");
-    n = 47; REQUIRE( string(nw.words(n)) == "forty-seven^P");
+    n = 47; REQUIRE( string(nw.words(n)) == "forty-seven");
 }

这个奇怪的控制字符只显示在差异中,并且只有在我尝试在失败后从差异或控制台复制/粘贴文本之后。添加特殊字符会导致测试通过。如果我在键盘上手动键入值“四十七”,特殊字符就会消失并且它FAILS。世界上到底发生了什么?这个 ^P 隐藏字符是什么?

numword.cpp 的来源如下:

#include "numword.hpp"

using namespace bw;
using namespace std;

numword::numword(uint64_t num) : number(num) {
}

static const char * unk = "?";

static const char * ones[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
static const char * tens[] = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};

const char * numword::words(uint64_t num) const {
    std::string asString;

    if(num < 20)
        asString = string(ones[num]);
    else if(num < 100){
        int index = ((int)num/10)-2;
        int x = ((int)num%10);
        asString += string(tens[index]) + "-" + string(ones[x]);
    } else
        asString = unk;

    char *result = (char*)malloc(asString.length());
    memcpy(result, asString.c_str(), asString.length());
    return result;
}

我刚刚做了一些研究,发现 ^P 是一个数据链接转义码 (DLE)。我仍然不确定如何键入它。我的 numword.cpp 逻辑如何添加它?我哪里错了?

4

1 回答 1

0

我发现了我的困境!控制字符是一个工件,因为我不是 null 从 words 方法终止我的字符串。从那以后,我添加了一个 nul 终止符,问题就消失了。(请不要在这里提及我明显的内存泄漏,我正在重新学习!)

更新的单词方法:

const char * numword::words(uint64_t num) const {
    std::string asString;

    if(num < 20)
        asString = string(ones[num]);
    else if(num < 100){
        int index = ((int)num/10)-2;
        int x = ((int)num%10);
        asString += string(tens[index]) + "-" + string(ones[x]);
    } else
        asString = unk;

    char *result = (char*)malloc(asString.length());
    memcpy(result, asString.c_str(), asString.length());
    result[asString.length()] = '\0';
    return result;
}
于 2018-08-17T17:39:21.353 回答