Archived

This topic is now archived and is closed to further replies.

mkoday

Best Way To Handle Strings

Recommended Posts

In C/C++ what is the best way to handle strings for DOS programming? Using fputs(), and gets() is what I am doing now, and having the string be a char array.

Share this post


Link to post
Share on other sites
Use STL strings.

  
#include <fstream>
#include <iostream>
#include <string>

using namespace std;
string str0, str1;
int main(int argc, char *argv[])
{
// assign strings easily

str0 = "Whoa! (Eat your heart out, Keanu)";
// read in from console

cout << "Enter any text you want: ";
cin >> str1;
// print to console

cout << str0 << endl;
// compare strings

if(str0 != str1)
// copy string

str0 = str1;
// and so on.

return 0;
}


The Definitive Useful Link:
SGI STL documentation

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
yep, use STL strings. The only issue you should have is that ifstreams and ofstreams take char* as parameters. However that problem is easily solved, with c_str(), a member function of string.

Share this post


Link to post
Share on other sites
Note that cin >> str1; does not do what you think it does, it skips whitespace, then puts one word into str1. You probably want getline(cin,str1); that copies everything up to ''\n'' and throws the newline away.

Share this post


Link to post
Share on other sites
c_str converts the string to a const char *, and the functions take a char *. The getline() does not work properly as it requires you to push enter twice to accept the input.

Share this post


Link to post
Share on other sites
That''s an overgeneralisation.

getline() works just fine UNLESS you have Visual C++ and you haven''t applied the fixes available on the Dinkumware site. (Use Google to find it...)

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
hey we never said anything is wrong with char* (though personally I think they are horrible) but I just recommend that people use strings, especially newbies who have enough to think about already. When he becomes 1337 and wants to take up using char* then that''s fine. I just think that people should use the STL until they actively decide not to. It is a good set of default types.

Share this post


Link to post
Share on other sites