The operator >> used on cin skips blanks.
To read all characters from an input stream, including blanks, use the get method:
char ch;
cin.get(ch);
Use the put method to output any character to an output stream: cout.put(ch);
Traditional C programs used arrays of characters to represent strings.
char greeting[] = "Hello, world!";
A C string is always terminated by the null character \0.
Therefore, the array size was one greater than the number of characters in the string.
The greeting character array above has size 14.
You cannot assign a string value to a C string array variable.
greeting = "Good-bye!";
Instead, you use the strcpy("string copy") function:
strcpy(greeting, "Good-bye!");
To compare two C strings, use the strcmp ("string compare") function: strcmp(str1, str2);
It returns a negative value if str1 comes alphabetically before str2.
It returns zero if they contain the same characters.
It returns a positive value if str1 comes alphabetically after str2.
C++ programs use the standard string class:
#include
using namespace std;
You can initialize string variables when you declare them:
string noun, s1, s2, s3;
string verb("go");
You can assign to string variables:
noun = "computer";
String concatenation:
s1 = s2 + " and " + s3;
String comparisons with == != < <= > >=
Lexicographic comparisons as expected.
Strings automatically grow and shrink in size.
A string keeps track of its own size.
Use the member function at to safely access a character of a string: s1.at(i)
s1[i] is dangerous if you go beyond the length.
Many useful member functions
str.length(), str.at(i), str.substr(position, length),
str.insert(pos, str2), str.erase(pos, length),
str.find(str1), str.find(str1, pos),
str.find_first_of(str1, pos),
str.find_first_not_of(str1, pos)