0

Input:9 notation

printf("Input N value\n");
scanf("%d",&N);
char X[N];
int i=0,N=0;
for (i=0;i<N-1;i++)
 {
scanf("%c",&X[i]);
}
X[N-1]='\0';


for (i=0;i<N-1;i++)
{
printf("%c",X[i]);
}

Expected output:notation Output:notatio

Why is this so?

1
  • corrected my answer! (Don't know why i missed that one) Commented Jan 1, 2015 at 11:29

2 Answers 2

1

When you read the length with your first scanf call you leave a newline in your input buffer.

At the second scanf call the first character read is the newline and then the rest. Adding a space before the %c in your second scanf string parameter will consume any left newlines.

scanf(" %c",&X[i]);

You also don't null terminate your string, before printing it.

X[N-1] = '\0' ;
Sign up to request clarification or add additional context in comments.

Comments

0

You dont have to substract 1 in your for loops, otherwise it will miss 1 character at the end!

This should work:

#include <stdio.h>

int main() {

    int charNumber, charCount;

    printf("Input N value\n>");
    scanf("%d", &charNumber);

    char text[charNumber+1];

    for (charCount = 0; charCount < charNumber; charCount++)
        scanf(" %c", &text[charCount]);

    text[charNumber] = '\0';

    for (charCount = 0; charCount <= charNumber; charCount++)
            printf("%c", text[charCount]);

    return 0;

}

You can also print the string with:

printf("%s", text);

2 Comments

You are doing the same mistakes as @Hari.
@2501 lol i looked at this older answer and saw it, updated it now.

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.