Skip to main content
GameDev.net gamedev.net
🔒 Locked

String Input

Started by lallous Jul 7, 2009 at 1:05 PM 2 replies 1.4k views
Original Post
lallous
lallous
Hello everyone, reading through the string and array chapter, I ended up with a couple of ways to manipulate and use strings or character arrays. So what do you recommend between the following methods: cin>>variable (ofcourse doesn't read spaces) cin.get(arrayname,sizeofarray)//arrayname is an array of type char gets(variable); cin.get(character); Which methodology do you recommend using? Thank You,
rip-off
rip-off
Perhaps you book hasn't reached std::string yet, but I usually find a combination of std::getline() and std::string works best for me. But it depends, if I were reading a file of arbitrary whitespace separated numbers, I would use operator>>().

I wouldn't use raw character arrays if it could be avoided.
lallous
lallous
Yes in fact my book did reach the string library but I forgot to mention it.
So it is best to use string accompanied with getline.

Thanks
rip-off
rip-off
No, it really does depend.

Files that are interesting to programs are usually formatted in particular ways. Some are line based, and getline() (often combined with re-parsing the line using std::stringstream) is a simple way to deal with such formats.

Some formats are free form, like XML. In this case, just read in a bunch of data at a time (maybe the entire file if possible) and do the parsing in memory. Obviously, for an XML file you would use an existing XML parsing library.

Many well known formats are binary, which means they have non-textual elements. These need routines for reading and writing to be written very carefully, taking care for such issues as data sizes and endianess.

My suggestion of getline() was motivated because many beginners start with simple interactive text formats. I think getline() is usually best for such programs.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.