Reputation: 311
I am writing a function that looks for the first 4 whole numbers separated by a comma in a string.
For example, if the string is:
123,4,9.5,av4,3,g1,1,6
the function will extract to a different array the numbers: 123,4,3,1
Everything works well until I try entering an input with a space in the middle, which is not supposed to be considered as a valid number, but then the loop stops once it bumps into the space. Is there a solution for that?
I'm not allowed to use any other library than stdio.h
.
Here's my code:
int getParameters(int parameters[], int size) {
char input[100];
int indexInput = 0, indexParameters = 0;
int skip = 0, numberSeen = 0, negativeSeen = 0;
int i = 0;
scanf("%s", input);
for ( ; input[indexInput]!= '\0' && indexParameters < size; ++indexInput) {
if (input[indexInput] == ',' && skip == 1) {
parameters[indexParameters] = 0;
skip = 0;
negativeSeen = 0;
} else if (input[indexInput] == ',' && negativeSeen == 1 && numberSeen == 1) {
printf(ERROR);
return -1;
} else if (input[indexInput] == ','&& numberSeen == 1) {
numberSeen = 0;
indexParameters++;
} else if (input[indexInput] == ',') {
continue;
} else if (input[indexInput] == '-' && skip == 1) {
continue;
} else if (input[indexInput] == '-' && numberSeen == 0 && input[indexInput+1] != '-') {
negativeSeen = 1;
} else if (input[indexInput] <= '9' && input[indexInput] >= '0') {
parameters[indexParameters] *= 10;
parameters[indexParameters] += input[indexInput] - '0';
numberSeen = 1;
} else {
skip = 1;
}
}
if (skip == 1)
parameters[indexParameters] = 0;
while (i < 4) {
printf("%d,", parameters[i]);
++i;
}
return 0;
}
Upvotes: 2
Views: 1463
Reputation: 96258
The name of the %s
format specifier is a bit misleading, it matches a sequence of non-whitespace characters. As you can see it's meant to read a word, not the whole string.
Perhaps you want to read a whole line?
Upvotes: 5