Search code examples
cscanfatoi

Build my own scanf function


For academic purposes, I have to build my own atoi() and scanf() function.

The first one was pretty simple but I'm having trouble with the second one.

first one:

int String2Inteiro (char s[])
{
    int j;
    int i=0;
    for(j=0; s[j]!= 0; j++) 
    {

        i=i*10 + s[j] - '0';
    }

    return i;
}

Now in the second one I'm having some issues that I think that are related to the stop condition. My first attempt was trying to stop after the cicle.

char dig;
int cont=0;

do
{
    dig=getchar();
    array[cont]=dig;
    cont++;
} while (dig!= '\n');

The second attempt was:

int counter=0;
char a;
char array[20];

while (a!='\n')
{
    a=getchar();
    vec[counter]=a;
    counter=counter+1;
}

I'm not sure if the enter is well represented or if i should had use '\13' (ASCII code of CR).

Thanks in advance,

André


Solution

  • You should break out of the loop as soon as you read the stop character, not after adding it to the array:

    while (counter < sizeof(array)) { // Prevent buffer overflow
        a = getchar();
        if (a == '\n') {
            array[counter] = 0; // Add trailing null to input string
            break;
        }
        array[counter] = a;
        counter++;
    }