I am writing this post because I am getting stucked trying to get all the negative numbers using sscanf. I code the following:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define M 1000
int main(void)
{
char a;
char enteros[M];
int output[M];
int newline = 0;
int count = 0;
int x = 0;
int index = 0;
int num = 0;
char *str;
while (fscanf(stdin, "%c", &a) != EOF)
{
enteros[count] = a;
count++;
}
enteros[count] = '\0';
str = enteros;
while (*str)
{
x = 1;
if (sscanf(str, "%d%n", &num, &x) == 1)
{
output[index] = num;
newline = 0;
index++;
}
str += x;
for (; *str; str++)
{
if (*str >= '0' && *str <= '9') /* positive value */
break;
if (*str == '-' && *(str + 1) >= '0' && *(str + 1) <= '9') /* negative */
break;
else if (!newline && isalpha((unsigned int)*str))
{
while (index != 0)
{
printf(" %d", output[index - 1]);
index--;
}
printf("\n");
newline = 1;
}
}
}
return 0;
}
My idea is to read from an input of integers and characters, get only integers (negatives and positives) into an array and, finally, reverse each number. But when I entered the following input:
1 8 4000 2 -23 end 51 87 end –4
–3 2 end
I get the following output:
-23 2 4000 8 1
87 51
2 3 4
I do not understand why I only get -23 instead of -23, -4 and -3 as the code received. Thanks for the help!