need help, can anyone send a link or have an answer
How do you declare strings in C++?
ignacionr2 has the most correct response to this question. The standard C++ library has a 'string' type in the standard ('std') namespace that allows you to declare and initialize an abstract string type.
Note, the header files for the standard C++ library no longer have the ".h" extension on them. So for I/O streams, you'd use: "#include %26lt;iostream%26gt;" and for strings, you'd use: "#include %26lt;string%26gt;".
To declare instances of a string, you could use:
std::string myString = "string one";
or
std::string myString("string two");
You can add a "using std::string;" to your local scope as a shortcut to avoid typing "std::" to qualify the standard string's namespace.
Reply:In C you only have a pointer to a char where you hope there's a series of chars ending with a null character (0).
C++ now has a Standard Library that lets you define controlled sequences of characters (or wide characters, or even other things) that needn't be finished by a zero. Look for std::basic_string.
Please update your C++ knowledge you people. We don't want to scare newbies by sharing an outdated view of the language. C++ is not the 'char *' language, not anymore.
Reply:Firstly, you need to the include strings.h header file.
A string can be declared as an array of char or as a pointer to a char block in memory. So you have:
// ... other header declarations
#include "stdio.h"
#include %26lt;iostream.h%26gt;
#include %26lt;strings.h%26gt;
//some code here
//now declare the string:
//method 1
char[20] string1; //declares a string of 20 chars
char * string2; //declares a string of undefined length. It can be as long as you wish, as long as your memory allows
Reply:Well, depending on your compiler, you can create strings like any other primitive data type:
string s = "Hello World!";
Reply:#include %26lt;iostream.h%26gt;
#include %26lt;string.h%26gt;
void main()
{
char a[10];
cin%26gt;%26gt;a;
cout%26lt;%26lt;a;
}
// ;)
Reply:In C++ a string is a reference to a character, so it's declared as a pointer to char (char*). You can find further information in string.h, or on programmersheaven.com
Reply:It is considered poor coding practice to use character arrays as strings in C++ as they tend to be vulnerable to buffer overflows and other nastiness. Use a C++ string.
#include %26lt;string%26gt;
using std::string;
string s = "Hello World";
If you later need to use an array of characters (because of outdated c code asking for it), you can do so with the c_str() member function (e.g. if you wanted to use printf).
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment