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?
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?
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' ;
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);