简体   繁体   中英

How can I put a user input value into strncpy?

So, I am trying to write an strncpy function. I want user to input the number of characters to be copied from source. I am doing something wrong, but I can't understand what. This is what I tried to do:

#include <stdio.h>
#include <string.h>
#define ARR_SIZE 20

int main() {
    char string[ARR_SIZE];
    int n, m;
    char s1[4], s2[4], nstr[m];
    printf("Enter the string:");
    gets(string);
    printf("The length of the string is: %ld\n", strlen(string));

    strcpy(s1, s2);
    printf("The original string is: %s\n", string);
    printf("The copy of the original string is: %s\n", string);
    
    printf("How many characters do you want to take from this string to create another string? Enter: \n");
    scanf("%d", &n);
    strncpy(nstr, s1, m);
    printf("%s\n", nstr);
}

(On top I tried some strlen and strcpy functions.) EDIT: I totally forgot to write what was the problem. Problem is I can't get the new string which is named nstr in my code. Even though I printed it out.

first of all, the whole code is just a bad practice.

Anyway, here is my take on your code which copies n characters of an input string to string_copy

#include <stdio.h>
#include <string.h>
#define ARR_SIZE 20

int main() {
    char string[ARR_SIZE];
    int n;
    printf("Enter the string:");
    gets(string);
    printf("The length of the string is: %ld\n", strlen(string));

    printf("The original string is: %s\n", string);

    printf("How many characters do you want to take from this string to 
    create another string? Enter: \n");
    scanf("%d", &n);
    if(n > strlen(string)){
        n = strlen(string);
        printf("you are allowed to copy maximum of string length %d\n", n);
    }

    char string_copy[n];
    strncpy(string_copy, string, n);
    printf("%s\n", string_copy);
}

note that using deprecated functions such as gets() isn't safe. use scanf() or fgets() instead.

refer to why you shouldn't use gets()

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