繁体   English   中英

如何告诉字符串读取 0 而不是中止?

[英]how do I tell the string to read the 0 and not abort?

我有一个带有数字的字符串,包括 0。不幸的是,该字符串将数字 0 识别为 \0 并完成读入。有没有办法将 0 解释为 0 并读取它? 我的程序是用 C++ 编写的。

char buf[] = { 23, 4, 0, 234, 8}
string test(buf);

对于这种情况,字符串“test”将包含 23 和 4。但对于我的情况,它应该包含 23、4、0、234 和 8。

这些方法对我来说不是一种选择:

string test "abc\0\0def"s;            
string test R"abc\0\0def";

我试图做string test(buf, 5); 就像下面建议的答案一样,但它没有用:

#include<cstring>
#include<iostream>
#include <string>

using namespace std;

int main()
{
     char buf[]={10, 20, 0, 30, 40};
     string test(buf, 5);
     cout<<test.length()<<endl;
     char final[5]={0,0,0,0,0};

     strncpy(final, test.c_str(),5);
     
     for(int i=0; i<5; i++)
     {cout<<(int)final[u]<<endl;}
}

您需要指定字符数:

string test(buf, size(buf));

此处使用std::size需要#include <iterator>


代替size(buf)您可以简单地编写5 ,或者以某种不同的方式获取数组大小。

请使用为您要使用的功能而设计的容器类型。 对于根本不是字符的数字,如果您需要在运行时更改大小,则应该使用std::vector 如果您的数据是恒定的,则可以使用std::array代替,它的开销更少。

还有一个问题,为什么要使用char作为数据类型,因为你有数字。 为什么不uint8_tint8_t

你应该避免使用strncpy strcpy甚至memcpy只要你对所有可用的容器类型都很好。 大多数容器都提供直接复制/移动到目标,而无需调用任何 c 样式函数。

顺便说一句: final是一个 C++ 关键字。 请不要将它用于函数或变量或类型的名称。

int main()
{
     std::vector<uint8_t> test{10, 20, 0, 30, 40};
     std::cout << test.size() << std::endl;
     std::vector<uint8_t> final_ = test; //copy, no special external func required

     // or if you really like to init 0 and overwrite
     std::vector<uint8_t> final2(5); // init with 5 times 0
     final2 = test; // copy;

     // cast is still needed to force cout to print number instead of char
     for ( auto c: final_ ) { std::cout << (uint16_t)c << std::endl; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM