【问题标题】:How can I put a user input value into strncpy?如何将用户输入值放入 strncpy?
【发布时间】:2021-06-29 09:43:19
【问题描述】:

所以,我正在尝试编写一个strncpy 函数。我希望用户输入要从源复制的字符数。我做错了什么,但我不明白是什么。这是我试图做的:

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

(在上面我尝试了一些 strlen 和 strcpy 函数。) 编辑:我完全忘记写出问题所在。问题是我无法在我的代码中获得名为 nstr 的新字符串。虽然我打印出来了。

【问题讨论】:

  • 有什么问题?
  • 尝试一次解决一个问题。 您试图同时实现用户输入和字符串复制,但出现了问题。编写两个程序,一个接受用户输入,另一个处理硬编码的字符串。只有当两者都工作得很好时,你才应该尝试将它们相吻合。

标签: c input scanf strncpy


【解决方案1】:

首先,整个代码只是一个不好的做法。

无论如何,这是我对您的代码的看法,它将输入字符串的 n 个字符复制到 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);
}

请注意,使用不推荐使用的函数(例如 gets())是不安全的。请改用 scanf() 或 fgets()。

参考why you shouldn't use gets()

【讨论】:

  • "%ld" 肯定与strlen() 返回的类型不匹配。谁或什么文字建议了该说明符?
  • 这只是一个虚拟示例,不能保证 100% 正确。它只是用尽可能少的修改回答了这个问题
  • 改写:char string_copy[n]; strncpy(string_copy, string, n); printf("%s\n", string_copy); 是错误代码 (UB),无论 n 是什么。 "%s" 需要 字符串 而string_copy 不是字符串。
  • 我不知道这次讨论的意义何在。如果我们想制作完美的代码,那么我会添加更多的条件和约束,例如(n 不允许小于 0)。克服它。否则一个简单的答案代码可能会增加三倍。我们不是在这里编写库代码;)
猜你喜欢
  • 1970-01-01
  • 2017-02-04
  • 2022-06-23
  • 1970-01-01
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
相关资源
最近更新 更多