Storing an item in a string
Question: In my code that I have ever entered for n, the compiler only allows me to input and output half. Why?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
scanf("%d\n",&n);
char *c= (char*)malloc((n+1)*sizeof(char));
c[n]='\0';
for(int i=0;i<n;i++)
{
scanf("%c",&c[i]);
}
for(int i=0;i<n;i++)
{
printf("%c",c[i]);
}
}
source to share
Change this:
scanf("%c",&c[i]);
:
scanf(" %c",&c[i]);
Output example:
Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
5
a
b
c
d
e
abcde
I discuss the arguments for this solution in Caution when reading char with scanf (C) .
PS: Am I doing malloc result? Not!
Also, since you are allocating memory dynamically, remember to free () at the end of yours main()
, for example:
free(c);
source to share
Ques. the compiler only allows you to input half the size of the array, why?
The cause of the problem:
scanf("%c",&c[i]) //Here %c takes enter key also as a part of input which reduces the input size to half.
So, there are mainly 2 solutions to your problem:
Sol. 1 => you need to include spaces, the break code will be the same.
scanf(" %c",c[i]) //use whitespace before %c
Sol. 2 => Do not enter one character at a time, please type all the input as a bundle at the same time, then press enter.
source to share