【发布时间】: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 的新字符串。虽然我打印出来了。
【问题讨论】:
-
有什么问题?
-
尝试一次解决一个问题。 您试图同时实现用户输入和字符串复制,但出现了问题。编写两个程序,一个接受用户输入,另一个处理硬编码的字符串。只有当两者都工作得很好时,你才应该尝试将它们相吻合。