简体   繁体   中英

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

I have a string with numbers, including 0. Unfortunately the string recognize the number 0 as \0 and finishes reading in. Is there a way to interpret the 0 as 0 and read it? My program is written in C++.

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

For this case the string 'test' will contain 23 and 4. But for my case it should contain 23, 4, 0, 234 and 8.

These ways are not an option for me:

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

I tried to do string test(buf, 5); like the answer below suggested, but it didn't work:

#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;}
}

You need to specify the amount of characters:

string test(buf, size(buf));

The use of std::size here requires #include <iterator> .


Instead of size(buf) you can simply write 5 , or obtain the array size in some different way.

Please use container types which are made for the functionality you want to use. For numbers, which are not characters at all, you should use std::vector instead, if you have the need of changing the size during runtime. If your data is constant, you can use std::array instead, which has less overhead.

Still there is the question, why you want to use char as data type, as you have numbers. Why not uint8_t or int8_t ?

You should avoid using strncpy strcpy or even memcpy as long you are fine with all the available container types. Most all containers offer direct copy/move to target without calling any c-style functions.

BTW: final is a C++ keyword. Please do not use it for names of functions or variables or types please.

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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