Value or String?

My philosophy is to treat the input as a string until I can confirm that it’s not. The question then rises as to how strings can best translate into a value.

When specific input is required, you can use the scanf() function, which is really quite powerful — but it’s stubborn. The scanf() statement halts a program as it waits for a variable type that may never come.

In my code, I just assume that all input is text. This assumption is safe because both values and text can be read as characters from the stream. I then use common library functions to translate values from text: atoi() for int values and atof() for float values. These functions do a great job translating text (ASCII) to values, interpreting weird input properly as either the value or as zero. They require the stdlib.h header file.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *strings[4] = {
        "123",
        "0.33",
        "7lucky",
        "string"
    };

    puts("  String\tAs int\tAs float");
    for(int x=0;xlt;4;x++)
    {
        printf("%d: %-7s\t%d\t%f\n",
                x+1,
                strings[x],
                atoi(strings[x]),
                atof(strings[x]));
    }

    return(0);
}

Most of the ugliness in this code comes from the printf() statement starting at Line 16. The knots and bows in the formatting string help create a readable table of values. Here’s the program’s output:

  String	As int	As float
1: 123    	123	123.000000
2: 0.33   	0	0.330000
3: 7lucky 	7	7.000000
4: string 	0	0.000000

If your code had to read the four sample strings as input, the translation done by atoi() and atof() wouldn’t clog the pipes. But if you want to know whether a string is specifically an int or float, more processing is necessary.

As an example, consider a CSV file where you don’t know the data fields. Now that’s a bad situation anyway, but just pretend: Your code reads in a string and then must determine the best format: char array, int, or float. Yes, it’s a guess, but you can make a good guess.

I can think of several approaches to solve this puzzle.

In one method, you can use atoi() or atof() and then compare the value with the original string. The sprintf() function can be used to translate the value back into a string, then run strcmp() on both to confirm the results.

Another way would be to examine the string character-by-character. If the string is all numbers, it’s probably an int. If the string is all numbers but also has a decimal point, it’s probably a float. Otherwise, the string is a string. Then again, the string 7lucky in the example did translate into the values 7 and 7.0, but that might not be what you consider a valid value.

In next week’s Lesson, I’ll present code that demonstrates both of these solutions.

Leave a Reply