My Code :
#include <stdio.h>
int main()
{
int size,i;
printf("Enter the size of the string: ");
scanf("%d",&size);
int arr[size];
printf("Enter the String: ");
for(i=0;i<size;i )
{
scanf("%d",&arr[i]);
}
printf("The string you've entered is: ");
for(i=0;i<size;i )
{
printf("%d ",arr[i]);
}
return 0;
}
I've tried to enter an array of numbers like: 10234, but the next statement is not getting executed, it's not showing me the printf statement i.e "The string you've entered is: ".
But it's working if I enter the array of numbers like: 1 0 2 3 4 (with spaces). How can I make it work without spaces too, can you help me with it ?.
CodePudding user response:
#include <stdio.h>
int main()
{
int size,i;
printf("Enter the size of the string: ");
scanf("%d",&size);
char arr[size];
printf("Enter the String: ");
for(i=0;i<=size;i )
{
scanf("%c",&arr[i]);
}
printf("The string you've entered is: ");
for(i=0;i<=size;i )
{
printf("%c ",arr[i]);
}
return 0;
}
CodePudding user response:
If you want to read string and convert digits to the int array:
size_t getsize(FILE *fi)
{
char buff[20];
size_t result = 0;
if(fgets(buff, sizeof(buff), fi))
{
if(sscanf(buff, "%zu", &result) != 1) result = 0;
}
return result;
}
int main()
{
size_t size,i;
printf("Enter the size of the string: ");
if(!(size = getsize(stdin))) goto error_exit;
do{
char str[size 2];
int arr[size];
printf("Enter the String: ");
if(!fgets(str, size 2, stdin)) goto error_exit;
for(i=0;i<size;i )
{
if(str[i] == '\n') break;
if(!isdigit((unsigned char)str[i])) goto error_exit;
arr[i] = str[i] - '0';
printf("%d ",arr[i]);
}
return 0;
}while(0);
error_exit:
printf("Error!!!\n");
return 1;
}
CodePudding user response:
Use scanf("", &arr[i]);
(1
added) to limit input to 1 non-white-space character.
Also better to check the return value of all scanf()
calls.