正在采取行动。通过字符。输入以在 c 中生成字符串

问题描述 投票:0回答:1

所以我确实尝试使用 for 循环,但每次我的输出都会跳过索引 0 的值,我只是不明白为什么...... 这是我的代码:

// take char by char input and print it as string

#include <stdio.h>

void input(){
    printf("this program takes char by char input for string\n");
    int length;
    printf("provide us with the total length of the string : ");
    scanf("%d",&length);
    char arr[length];
    char placeholder;
    for(int i=0;i<length;i++){
        if(i==length){
             arr[i]='\0';
        }
        printf("input char[%d] : ",i);
        scanf("%c",&placeholder);
        printf("\n");
        arr[i]=placeholder;
        }
}

int main(){
    input();
}

我得到的输出: 该程序将字符逐字符输入为字符串 为我们提供字符串的总长度:10 input char[0] : // 它被跳过了
input char[1] : // 这是我可以输入值的地方

c
1个回答
0
投票

对于初学者来说,for 循环中的 if 语句

for(int i=0;i<length;i++){
    if(i==length){
         arr[i]='\0';
    }
    //...

由于for循环的条件,永远不会执行。

其次是 scanf 的调用

scanf("%c",&placeholder);

按 Enter 键后还会读取存储在输入缓冲区中的新行字符

'\n'

要跳过空格字符(包括换行符)

'\n'
,您应该使用以下转换规范

scanf(" %c",&placeholder);
   

注意格式字符串中的前导空格。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.