Reputation: 15
I need help figuring out how to take input in specific format in C
{1,2,3,4}
// that is right input - numbers in {} separated by comma.
znamky = (int*) malloc (n * sizeof(int)); // I allocate memory here
if (znamky == NULL)
return EXIT_FAILURE;
printf("Pocty bodu:\n");
scanf("%c",&overeni[0]); // here I check if the first character is {; if not I exit program
if (overeni[0]!=zavorka[0])
{
printf("Nespravny vstup.\n");
return EXIT_FAILURE;
}
while (scanf("%d",&znamky[count])!=EOF) //here I continue loading numbers, and char fight
{ //if the character after number is "," i load another
if (scanf("%c",&znaminko[0])==1) //number, if it is "}"I exit the while cycle
{ // else I exit the program
if (znaminko[0]==carka[0]) // if equals ","
{
printf("sdf\n");
count++;
if (count==n) // if I run out of memory I allocate more
{
n = n*2;
znamky = (int*) realloc (znamky, n * sizeof(int) + 4);
}
continue;
}
if (znaminko[0]==zavorka2[0]) // if equals "}"
count++;
printf("utikam\n");
break;
}
else
{
printf("Nespravny vstup\n");
return EXIT_FAILURE;
}
}
printf("%d ",count); //here I just print length of my array
printArray(znamky,count);
free(znamky);
return 0;
My problem is this: when I run the code and give it right input, it works just fine, but if I for example input {2 and press enter it thinks, that the input is equal "}"and exits the cycle. Why does it think that? Above when I compare char to "{" it seems to be working fine... Also any tips on how to improve the code are welcome, I am still new to programming so I don't see all the obvious mistakes. Thanks a lot.
My problem is this: when I run the code and give it right input, it works just fine, but if I for example input {2 and press enter it thinks, that the input is equal "}"and exits the cycle. Why does it think that? Above when I compare char to "{" it seems to be working fine...
Also any tips on how to improve the code are welcome, I am still new to programming so I don't see all the obvious mistakes.
Upvotes: 0
Views: 107
Reputation: 44274
but if I for example input {2 and press enter it thinks, that the input is equal "}"
The problem is here:
if (znaminko[0]==zavorka2[0]) // if equals "}"
count++;
printf("utikam\n");
break;
it should be:
if (znaminko[0]==zavorka2[0]) // if equals "}"
{
count++;
printf("utikam\n");
break;
}
Upvotes: 2