1

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

7
  • 2
    if(i==length) This condition cannot possibly be true. It is inside for(int i=0;i<length;i++) loop. so i<length is true inside. You ar reassigning arr[i] anyway later, so this is doubly useless. Commented Dec 19, 2024 at 8:05
  • 2
    When asked for length you entered 10{newline}, but %d only reads the 10 and leaves the {newline} buffered, so when you subsequently use %c it reads the {newline} for 'char[0]' and then your next input into 'char[1]` etc. I'm sure this is a dupe but don't have one bookmarked. @n.m. also if you did access arr[length] that would be outside the valid bounds of the array causing Undefined Behavior Commented Dec 19, 2024 at 8:05
  • As for your immediate question, the first character you read is the newline that is left in the input buffer after the number. I recommend never using scanf. Read input lines with fgets, then parse them. Commented Dec 19, 2024 at 8:06
  • @n.m.couldbeanAI Never is a long time. fgets() is weak when reading user input that may contain null characters. scanf("%999[^\n]%n", ...) is a building block to read such. Standard C still lacks a real good line input function. Commented Dec 19, 2024 at 11:23
  • @chux? User input contains null characters in the middle of a line? Then everything after that is ignored. User wants something else? Close, wontfix.If valid user input is supposed to contain embedded null characters, then it's mot lines. It's binary data. Commented Dec 19, 2024 at 16:45

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Thank u for explaining the answer in such detail. it made me happy. Thank u for helping me and have a great day :)
@Rudraksh_pd No at all. We, beginners, should help each other.:)
"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." --> Maybe not. Consider unsigned len; if ( scanf("%u", &len) == 1 && len > 0 ) { char arr[len]; //... }. Should user enter "-1\n", code will attempt arr[UINT_MAX] -- certainly a troublesome case. int len; if ( scanf("%d", &len) == 1 && len > 0 ) ... does not have this trouble. unsigned would make sense with if ( scanf("%u", &len) == 1 && len > 0 && len <= SOME_SANE_LIMIT_LIKE_1000).
@chux If you will enter a negative number for the conversion specifier u then the call of scanf will fail.
"enter a negative number for the conversion specifier u then the call of scanf will fail." --> the C spec does not agree. "u Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtoul" Try #include <stdio.h> int main() { unsigned u = 42; int i = scanf("%u", &u); printf("%d %u\n", i, u); } and enter "-1\n". I get 1 4294967295. strtoul("-1", 0, 10) nicely returns a positive with errno still 0.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.