C ++ Equivalent to strncpy

What is equivalent strncpyin C ++? strncpyworks in C, but does not work in C ++.

This is the code I'm trying to do:

string str1 = "hello"; 
string str2; 
strncpy (str2,str1,5);
+3
source share
7 answers

The C equivalent strncpy()(which, BTW, is written std::strncpy()in C ++ and must be found in the header <cstring>) is an assignment operator std::string:

std::string s1 = "Hello, world!";
std::string s2(s1);            // copy-construction, equivalent to strcpy
std::string s3 = s1;           // copy-construction, equivalent to strcpy, too
std::string s4(s1, 0, 5);      // copy-construction, taking 5 chars from pos 0, 
                               // equivalent to strncpy
std::string s5(s1.c_str(), std::min(5,s1.size())); 
                               // copy-construction, equivalent to strncpy
s5 = s1;                       // assignment, equivalent to strcpy
s5.assign(s1, 5);              // assignment, equivalent to strncpy
+10
source

strncpyworks with an array of characters, and it works great in C ++, as well as in C.
If you use a strncpycharacter array in C ++, and this doesn't work, perhaps due to some error in your C ++ code: show us if you want some help.

(.. std::string), , :

std::string a = "hello!";

. , , strncpy: , .

, : std::string , n , , .

+3

basic_string:: copy std::string const char* std:: copy, .

"strncpy fail in ++", ?

+2

strncpy ++ - strncpy.

- , , .

0

strncpy cstring header ++. C- , C, , ++

#include<cstring>
using namespace std;
int main(int argc, char *argv)
{
   char *s,*v;
   strncpy(s,v,0);
}

, . ++, string . , .

0

strncpy does not accept std::stringas arguments. Prototype

char * strncpy ( char * destination, const char * source, size_t num );

and the link provided gives a description and an example of how to use it.

I would stick std::string, but if you need to, use the method c_str() std::stringto get the char *pointer

0
source

There is no built-in equivalent. You need to flip your own strncpy.

#include <cstring>
#include <string>

std::string strncpy(const char* str, const size_t n)
{
    if (str == NULL || n == 0)
    {
        return std::string();
    }

    return std::string(str, std::min(std::strlen(str), n));
}
-1
source

Source: https://habr.com/ru/post/1785219/


All Articles