首页 > 解决方案 > 打印字符串的前 N ​​个字符 (C)

问题描述

我的目标是使用简单的 for 循环打印出字符串的前 N ​​个字符(len变量)。但是,代码似乎不起作用。例如,输入printFrstChars("Example",3)的代码应该打印出来Exa,但它不会打印出任何东西

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

void printFrstChars (char inp[], int len)
{
    for(int i = 0; inp[i] != '\0' && i <= len; i++){
        printf("%s", inp[i]);

    }

}

int main ()
{   
    int len = 0;
    char inp[100];
    printf("Input string and length:\n");
    scanf("%99s %d", &inp, &len);
    printFrstChars(inp, len);
   

    return 0;
}

我多次检查代码,我(显然)没有找到导致这种情况的错误。我猜这要么是一个足以隐藏在我初学者眼中的错误,要么是整个方法都是错误的。

标签: arrayscstring

解决方案


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

void printFrstChars (char inp[], int len)
{
    for(int i = 0; inp[i] != '\0' && i < len; i++){
        printf("%c", inp[i]);
    }
    printf("\n");
}

int main ()
{   
    int len = 0;
    char inp[100];
    printf("Input string:\n");
    scanf("%99s", inp);
    printf("Input length (99 or less):\n");
    scanf("%d", &len);
    printFrstChars(inp, len);
   

    return 0;
}

分离输入,扫描到inp而不是,用格式&inp打印每个字符,然后迭代 while (之后打印新行)。我的 2 美分。%ci < len


编辑

感谢@AndrewHenle 指出溢出。格式说明%99s符最多只能读取 99 个字符(并且提示也说明了这一点)。


推荐阅读