I have a software that reads from a file. Each object in the software takes 7 in
ID: 654935 • Letter: I
Question
I have a software that reads from a file. Each object in the software takes 7 inputs viz.
string string string float string float int
I have an input file. It contains a number of input values. If input for one object is like:
hss cscf "serving cscf" 32.5 ims 112.134 124
(Note: when an object's variable needs multi word string, I used "....", for single word string, it is without quotes)
How can I read it using ifstream? (I searched google but didn't find.)
I tried to read entire line using getline and but again got stuck when it came to find out whether its a single word or multi word input! I thought to read a line and then search char by char. If its '"', I know its a multi word. But I stuck when it comes to an integer or float. For char, you can use
if(line[i]>='a'&&line[i]<='z')
but how to go ahead when integer or float is the next value?
Please give some suggestions for this.
Explanation / Answer
You can differentiate numbers from words by looking at the characters within them. Basically, if a word contains exclusively [0-9.], you can assume it's a number.
In the same way, if an assumed number contains only [0-9], it's an integer. Otherwise, it's a float.
Beware of edge cases:
Cultures matter. In French, for example, you don't write 19.95, but 19,95. Even worse, the number 1 582.16 can be written 1582.16, 1,582.16, 1.582,16, etc., depending on the culture.
How do you escape strings? What if a multiword string contains a quote character?
Unicode can make things difficult, since unicode characters can be normalized and decomposed.
What if, one day, you need to have a word which has only digits, but still be interpreted as a word?
Side note: couldn't you reuse an existent format, like JSON, with already written and tested parsers? See also: How are new file formats constructed?
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.