How can I parse text input and convert strings to integers?
I have a file input, in which i have the following data.
1 1Apple 2Orange 10Kiwi
2 30Apple 4Orange 1Kiwi
and so on. I have to read this data from file and work on it but i dont know how to retrieve the data. I want to store 1(of 1 apple) as integer and then Apple as a string. I thought of reading the whole 1Apple as a string. and then doing something with the stoi function.
Or I could read the whole thing character by character and then if the ascii value of that character lies b/w 48 to 57 then i will combine that as an integer and开发者_如何学运维 save the rest as string? Which one shall I do? Also how do I check what is the ASCII value of the char. (shall I convert the char to int and then compare, or is there any inbuilt function?)
How about using the fscanf()
function if and only if your input pattern is not going to change. Otherwise you should probably use fgets()
and perform checks if you want to separate the number from the string such as you suggested.
There is one easy right way to do this with standard C library facilities, one rather more difficult right way, and a whole lot of wrong ways. This is the easy right way:
- Read an entire line into a
char[]
buffer usingfgets
. - Extract numbers from this line using
strtol
orstrtoul
.
It is very important to understand why the easier-looking alternatives (*scanf
and atoi
) should never be used. You might write less code initially, but once you start thinking about how to handle even slightly malformed input, you will discover that you should have used strtol
.
The "rather more difficult right way" is to use lex
and yacc
. They are much more complicated but also much more powerful. You shouldn't need them for this problem.
精彩评论