0

what can i and cant i use each one for

what is the difference between the char 'a' and the string "a"??

16th Jan 2017, 2:54 AM
jonathin
8 ответов
+ 6
string* and a char* are fundamentally different types. The difference between a string and a char* is that the char* is just a pointer to the sequence. This approach of manipulating strings is based on the C programming language and is the native way in which strings are encoded in C++. C strings are a bit tricky to work with - you need to be sure to allocate space for them properly, to avoid walking off the end of the buffer they occupy, to put them in mutable memory to avoid segmentation faults, etc. The main functions for manipulating them are in <cstring>. Most C++ programmers advise against the use of C-style strings, as they are inherently harder to work with, but they are still supported both for backwards compatibility and as a "lowest common denominator" to which low-level APIs can build off of. A C++-style string is an object encapsulating a string. The details of its memory management are not visible to the user (though you can be guaranteed that all the memory is contiguous). It uses operator overloading to make some common operations like concatenation easier to use, and also supports several member functions designed to do high-level operations like searching, replacing, substrings, etc. They also are designed to interoperate with the STL algorithms, though C-style strings can do this as well. In short, as a C++ programmer you are probably better off using the string type. It's safer and a bit easier to use. It's still good to know about C-style strings because you will certainly encounter them in your programming career, but it's probably best not to use them in your programs where string can also be used unless there's a compelling reason to do so.
16th Jan 2017, 4:00 AM
Alex
Alex - avatar
0
string is an array of characters. in this case the string is has a length of 2, the character 'a' and the null character '\0'.
16th Jan 2017, 2:59 AM
Nikunj Arora
Nikunj Arora - avatar
0
can i still use the char in loops?
16th Jan 2017, 3:02 AM
jonathin
0
that question is very vague. what exactly are you trying to do?
16th Jan 2017, 3:03 AM
Nikunj Arora
Nikunj Arora - avatar
0
im jsut trying to get a better grasp on the subject i just started so if i put int 'a'=20 if(a>19) {cout<<true}; {return 0} the data type of a doesnt matter right
16th Jan 2017, 3:09 AM
jonathin
0
i am just trying to get a better grasp on the subject i just started data types so like if i say am making a loop and put int 'a'=20
16th Jan 2017, 3:10 AM
jonathin
0
i assume a lot of this doesnt really become neccesary until i write much more complex code
16th Jan 2017, 3:11 AM
jonathin
0
playing around with the code is absolutely recommended for learning. keep it up.
16th Jan 2017, 3:17 AM
Nikunj Arora
Nikunj Arora - avatar