Best Way To Handle Strings

Started by
5 comments, last by mkoday 22 years, 5 months ago
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.
Advertisement
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
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.
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.
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.
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...)
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.

This topic is closed to new replies.

Advertisement