Issue
I wrote a code in C to print the id number (could be combination of both numbers and letters) of the employee. The compiler takes the id number as an input but it is printing nothing. At first, I use 'printf' but it is not working so then I googled to end up with that the output is sometimes buffered for performance reasons in many systems. I got many possible answers in some following threads-
- simple c program not printing output
- Why does printf not flush after the call unless a newline is in the format string?
- printf not printing on console
However, I tried all of the possibilities (being a beginner, implementation can be wrong), but none worked out for me [given as comments]. I have the code like following. Any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int* ptr;
int m;
char n;
printf("Id number of employee 1:\n");
printf("Enter your id number length\n");
scanf("%d", &m);
printf("%d\n", m);
ptr = (int*) malloc (m *sizeof(int));
printf("Enter your id number:\n");
scanf("%s", &n);
// fflush( stdout );
// fprintf(stderr, "The id number of emploee 1 is %s", n);
// setbuf(stdout, NULL);
// setvbuf(stdout, NULL, _IONBF, 0);
// setvbuf (stdout, NULL, _IONBF, BUFSIZ);
// printf("The id number of employee 1 is %s\n", n);
printf("The id number of employee 1 is %s", n);
return 0;
}
Solution
As it was said in the comment section "a single char can't hold a string of letters". There were other things here to make a better code, e.g. freeing allocated memory. Here is code example of how it can be done:
int main()
{
char* ptr;
int m;
printf("Id number of employee 1:\n");
printf("Enter your id number length\n");
scanf("%d", &m);
ptr = (char*)malloc(m * sizeof(char) + 1);
if (ptr == NULL) {
printf("Allocation faild...");
return 1;
//you can call main to try again...
}
printf("Enter your id number:\n");
scanf("%s", ptr);
//scanf is not reliable, you can use a loop to enter all characters
//to the char array or validate scanf.
printf("The id number of employee 1 is %s",ptr);
// dont forget to free the allocated data
free(ptr);
return 0;
}
Answered By - Nevo Goldman