Start New Discussion within our Software Development Community

Hello,
I am tryinng to write a program that uses the cin.getline() function to get a users input, but I only need the numbers from this. The problem I am having is when I enter a number then other character it will count the characters after the numbers as numbers as well. Can someone tell me what I am doing wrong.

Code:

char getToken(char Entry[], int &pos)
{
    int j=0, lol;
    int Token[MAX_NAME_LENGTH];

    if (isalnum(Entry[pos]))
    {
        j=0;
        while(isalnum(Entry[pos]))
        {
            Token[j] = Entry[pos];
            Token[j] = Token[j] - '0';
            cout << Token[j] << endl;
            pos++;
            j++;
        }

        int total = 0;       
        for(int i = 0; i < j; i++)
        {
            total = (total * 10) + Token[i];
        }
        cout << "Total: " << total << endl;
    }
    else
    {               // if it finds a string it'll just ++ the pos no matter how  
        pos++;      //many spaces

    }
}

Sample Run:
Enter a string of characters: 54people are 1number1
5
4
64
53
63
64
60
53
Total: 61000053
49
66
53
Total: 5613
1
62
69
61
50
53
66
1
Total: 79565961
Press any key to continue . . .

I didn't really know what 'isalnum' does so i checked the c++ reference site and it says "Check if character is alphanumeric. Checks whether c is either a decimal digit or an uppercase or lowercase letter." So that seems to be the issue ? May be you should use 'isdigit' which is in the same header.

This article has been dead for over six months. Start a new discussion instead.