I am writing a program which allows the user to enter a number between 1 and 9 inclusive. Then display the width of output according to the number entered by the user. E.g. if 1 is entered, the program should print out "Your input is 1". If the 5 is entered, the program should print out "Your input is XXXXX5" [X = space]
So what I did what initializing a char array of size of the integer entered which is responsible for the width. Then initialize the char array with ' ' accordingly using for loop.
Everything works fine with number 1 to 8. But when I entered 9, there would be random characters before the digit such as "Your input is �@9".
What is happening? It seems like the compiler did not add the string terminator for the case of 9. Then it works fine when I manually set the last char to be '\0'.
Here are my codes:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char * argv[]){
int num;
do{
//prompt user to enter an int
printf("Please enter an integer between 1 and 9 inclusive: ");
scanf(" %d", &num);
//check if the number is between 1 and 9
if (num < 1 || num > 9) puts("You have enter an invalid integer! Try again!");
//ask for input unless valid
}while(num < 1 || num > 9);
char space[num]; //max width is num-1 but 1 more slot for string terminator
//initiate the string according to the width
for (int i = 0 ; i < num - 1 ; i++){
space[i] = ' ';
}
//space[num - 1] = '\0';
//display int according to the width
printf("Your input is %s%d\n", space, num);
return 0;
}
//space[num - 1] = '\0';