首页 > 解决方案 > 我怎样才能更正我的代码?我的代码的主要目标是从另一个字符串初始化新字符串,只需复制 C 中的 n 个首字母

问题描述

你能给我建议来纠正我的代码吗?它应该从另一个字符串初始化new_string,并复制该n字符串的第一个字母。输出应该是字符串。但是我的代码什么也没打印。我该如何解决?

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char str[99];
    int n, i, len;
    printf("Enter a string:");
    scanf("%s", str);
    printf("enter n:");
    scanf("%i", &n);
    if (n > len) {
        n = len;
    }
    char *new_string = malloc(n + 1);
    for (int i = 0; i < n; i++) {
        new_string[i] = str[i];
    }
    new_string[i] = '\0';
    printf("STring:%s", new_string);

    return 0;
}

标签: cterminalcomputer-science

解决方案


您可以按照djyotta在评论中的strncpy建议使用:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void)
{
    char str[100];
    printf("Enter string: ");
    /*
     * take spaces into account (optional),
     * prevent buffer overflow and
     * check return value of `scanf`
     */
    if (scanf("%99[^\n]", str) != 1) {
        fprintf(stderr, "Error: invalid input\n");
        return EXIT_FAILURE;
    }

    int n;
    printf("Enter index: ");
    /* check return value of `scanf` */
    if(scanf("%d", &n) != 1) {
        fprintf(stderr, "Error: invalid input\n");
        return EXIT_FAILURE;
    }

    /* initialize `len` */
    int len = strlen(str);
    if (n > len)
        n = len;
    char *new_str = malloc(n + 1);

    strncpy(new_str, str, n);

    printf("New string: %s\n", new_str);

    return EXIT_SUCCESS;
}

或者您可以进行以下代码注释中解释的更改:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void)
{
    char str[99];
    printf("Enter string: ");
    /*
     * take spaces into account (optional),
     * prevent buffer overflow and
     * check return value of `scanf`
     */
    if (scanf("%99[^\n]", str) != 1) {
        fprintf(stderr, "Error: invalid input\n");
        return EXIT_FAILURE;
    }

    int n;
    printf("Enter index: ");
    /* check return value of `scanf` */
    if(scanf("%d", &n) != 1) {
        fprintf(stderr, "Error: invalid input\n");
        return EXIT_FAILURE;
    }

    /* initialize `len` */
    int len = strlen(str);
    if (n > len)
        n = len;
    char *new_str = malloc(n + 1);

    for (int i = 0; i < n; ++i)
        new_str[i] = str[i];

    /* you don't need `i` here */
    new_str[n + 1]= '\0';
    printf("New string: %s\n", new_str);

    return EXIT_SUCCESS;
}

推荐阅读