** 更新
我正在试图了解为什么/为什么XCode实际上在删除我的C ++源时在我的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");
}
这个奇怪的控制字符仅在diff中显示,并且仅在失败后我尝试从diff或控制台复制/粘贴文本之后才显示。添加特殊字符会使测试通过。如果我在键盘上手动输入值“四十七”,则该特殊字符将消失并且失败。世界上正在发生什么?这个^ 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;
}
我只是did some research,发现^ P是数据链接转义码(DLE)。我仍然不确定如何键入它。我的numword.cpp逻辑如何添加它?我要去哪里错了?
答案 0 :(得分:0)
我发现了自己的困境!控制字符是一种伪像,这是因为我不是如何从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;
}