Saturday, May 9, 2009

Strings in C++?

Why can't I compile this program in Turbo C++\


#include%26lt;iostream.h%26gt;


#include%26lt;conio.h%26gt;


#include%26lt;strng.h%26gt;


void main()


{


string c;


cin.getline(c,10);


cout.write(c,10);


getch();


}

Strings in C++?
Fix the include statement.





#include%26lt;string%26gt;


using namespace std;





After doing that, the compiler error about 'string' being unidentified should go away.





Now you will get compile errors about using 'c' as if it were a char* in getline. It's not, it's a class basic_string and getline() wants a char*





Though basic_string has a .c_str() method to convert itself into to a const char*, that's not good enough and the compiler will still complain. getline( ) needs a non-const char*. Even if you forcefully cast it to a char*, you'll get an access violation at runtime.





To use getline, you'll need a char*. You can then assign that to the string. It's really not the best example of using a string class, because you're calling methods that won't take a string, and you're not using any of the cool stuff that the string class will do for you. This will compile and run, though:





string c;


char read[10];


cin.getline(read,10);


c = read;


cout.write(c.c_str(),10);


getch();
Reply:you mispelled string.





#include %26lt;string.h%26gt;





if that doesn't, then do it manually with


char mystring[10]
Reply://Ahmm it's the string...


//there is no string or boolean on c++


{


char c[100];//Or char *c;


cin.getline(c,10);


cout.write(c,10);


getch();


}
Reply:try loading %26lt;string.h%26gt;


No comments:

Post a Comment