代码之家  ›  专栏  ›  技术社区  ›  Rudraksh_pd

取炭。通过char。c中创建字符串的输入

  •  1
  • Rudraksh_pd  · 技术社区  · 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 输入char[0]://它被跳过了
    输入char[1]://这是我可以输入值的地方

    1 回复  |  直到 1 年前
        1
  •  1
  •   Vlad from Moscow    1 年前

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

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

    由于for循环的条件,永远不会执行。此外,在任何情况下,if语句都是无效的,因为数组的有效索引范围是 [0, length) 。即使用等于以下值的索引 length 导致阵列外的内存被覆盖。

    其次,scanf的呼吁

    scanf("%c",&placeholder);
    

    同时读取新行字符 '\n' 按下Enter键后存储在输入缓冲区中的数据。

    跳过空白字符,包括新行字符 n 您应该使用以下转换规范

    scanf(" %c",&placeholder);
       
    

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

    还要记住,您应该检查变量的值是否 长度 输入的值是否大于零。例如,类似

    if ( scanf("%d",&length) == 1 && length > 0 )
    {
       char arr[length];
       //...
    }
    else
    {
       //...
    }
    

    尽管无论如何,最好声明变量 长度 具有无符号整数类型( unsigned int size_t )而不是带符号整数类型 int .