See this main
:
int main(void)
{
int i;
int ch;
char str[512];
fgets(str, sizeof str, stdin);
for (i = 0; i <= (strlen(str)); i++)
{
if (str[i] != '\0' && str[i] != '\n')
{
int num = atoi(&str[i]);
printf("%d\n", num);
}
}
return 0;
}
I want to get line with numbers from user and get all the numbers without any spaces
or tabs
.
For example:
The input 1 2 3
.
But in this case this the output:
1
2
2
3
3
So why i received 2
and 3
twice?
The solution with
strtok
isn't that hard either:Though do keep in mind that it's a bit iffy in that it uses hidden state (not good for multithreaded programs), and of course it modifies the input string, so it can't be a constant (but why would you do that).
From the ref of
atoi()
:That means that if you give as input to that function " 2", it will return 2.
Change this:
to this:
and you will get:
Here is a tip about debugging this code: In your output, you got 2 and 3 twice, but not 1.
In other words, you get the number that were after a space twice. 1 didn't have a space before it.
This should make you thing that there is something spooky about the spaces there.
Indeed, you would enter the body of the if statement, even if
str[i]
was a space!By adding a condition to check if the current character is not a space, to enter the boby of the if statement, you actually skip the spaces.
Because the you also pass the position of the string which starts with spaces. they get the first number to be
2
and3
respectively twice. That is what is returned.Prints:
For the purpose of tokenizing you can use
strtok
and to convert it to numberstrtol
etc. These provides much better control over the error cases thanatol/atoi
do.It is a good idea to always think of error handling. What if the user wrongly press space and tabs. So first remove spaces and tabs if exist :
and then use
atoi()
.Here's how I would do it:
This uses
strtol()
so it will also handle negative numbers; if this is incorrect you can of course add checks to filter them out. I think this is way better than anything usingstrtok()
.When it reaches the space character in the input it will call
atoi()
with" 2 3"
(resulting in 2) and later on" 3"
(resulting in 3) which creates the unexpected numbers.