Rudraksh_pd
Rudraksh_pd

Reputation: 25

taking char. by char. input to make a string in c

so i did try it with using a for loop but every single time my output skips the value of index 0 and i just dont understand why.... here is my code :

// 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();
}

the output im getting : this program takes char by char input for string provide us with the total length of the string : 10 input char[0] : // it got skipped
input char[1] : // this is where i can enter value

Upvotes: 1

Views: 67

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311028

For starters this if statement within the for loop

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

is never executed due to the condition of the for loop. Moreover in any case this if statement is invalid because the valid range of indices for the array is [0, length). That is using an index equal to the value of length results in overwritting memory outside the array.

Secondly this call of scanf

scanf("%c",&placeholder);

reads also the new line character '\n' that stored in the input buffer after pressing the Enter key.

To skip white space characters including the new line character '\n' you should use the following conversion specification

scanf(" %c",&placeholder);
   

Pay attention to the leading space in the format string.

Also bear in mind that you should check whether the value of the variable length was inputed and whether it is gretaer than zero. For example something like

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

Though in any case it would be better to declare the variable length as having an unsigned integer type (unsigned int or size_t) instead of the signed integer type int.

Upvotes: 2

Related Questions