I’m making a program which is getting inputs from the user, while each input contains ints delimited with spaces. e.g “2 3 4 5”.
I implemented the atoi function well, but, whenever I try to run on the string and “skip” on the spaces I get a runtime error:
for(int i=0, num=INIT; i<4; i++)
{
if(input[i]==' ')
continue;
string tmp;
for(int j=i; input[j]!=' '; j++)
{
//add every char to the temp string
tmp+=input[j];
//means we are at the end of the number. convert to int
if(input[i+1]==' ' || input[i+1]==NULL)
{
num=m_atoi(tmp);
i=j;
}
}
}
In the line ‘if(input[i+1]==’ ‘…..’ I get an exception.
Basically, I’m trying to insert just “2 2 2 2”.
I realized that whenever I try to compare a real space in the string and ‘ ‘, the exception raises.
I tried to compare with the ASCII value of space which is 32 but that failed too.
Any ideas?
The problem is that you don’t check for the end of the string in your main loop:
should be:
Also, don’t use
NULLfor the NUL char. You should use'\0'or simply0. The macroNULLshould be used only for pointers.That said, it may be easier in your case to just use
strtoloristringstreamor something similar.