std::string Class
A string is not an array, but a class in C++. A string using a std::string class can be increased in length.
#include <string>
std::string name;
std::cin >> name;
also possible to assign and append. It is intuitive and secure.
string firstName = "Pury";
string fullName = "Onion";
// assignment
fullName = firstName;
// appending
fullName += "Bab";
concatenation:
string firstName = "Pury";
string lastName = "Bab";
string fullName;
fullName = firstName + " " + lastName;
We can use the relational operator.
if (firstName1 == firstName2)
{
// ...
}
// compares the order in dictionary
if (firstName1 > firstName2)
{
// ...
}
size( ), length( ) : return the length of a string
cout << name.size() << endl;
cout << name.length() << endl;
c_str( ) : const char* / returns a pointer to the start address of the character array of the string.
string line;
cin >> line;
const char* cline = line.c_str();
We can access a character in a string in the same way as C.
string name = "Puribab";
char letter = name[1];
name[3] = 'y'; // function that calls data by reference
at( ) : returns a reference to a character at a given position in a string (Not used much.)
char letter = name.at(1);
name.at(3) = 'y';
Reading one line.
string mailHeader;
getline(cin, mailHeader); // before '\n'
getline(cin, mailHeader, '@'); // before '@'(delimiter)
getline( ) retrieves the characters from the stream and stores them in a string. When meets end-of-file, it stops. (Then the value of eofbit becomes 'true'.)
<sstream>
std::istringstream
- cin, but not from the console, from a string.
- sscanf( ) of C
std::ostringstream
- cout, but not to the console, from a string.
- sprintf( ) of C
not used much.
+) cout and cin are streams either.
C Header
Use it. For performance.
#include <cstring> // <string.h>
#include <cstdio> // <stdio.h>
#include <cctype> // <ctype.h>
Memory Usage Process of the String Class
string line;
line = "HWI";
line += "Nice to meet you!";
The string class of C++ holds 16 bytes of memory and copies memory when inputting a new string. When another string that can not be stored in the 16-byte memory is newly input, it holds other 32 bytes of memory. Then it copies the existing memory to the new memory, moves the pointer, erase the existing memory, and copies the new input memory.
- Heap memory allocation is slow.
- Memory fragmentation problem
- The increase in internal buffers may not be safe in a multitreaded environment.
So, many programmers still use char[ ] with sprintf.
Memory Usage Process of c_str( )
string line = "HWI";
const char* cline = line.c_str(); // a pointer to 'const char', not a const pointer

'College Study > C++ (ENG)' 카테고리의 다른 글
[C++] File I/O (ENG) (0) | 2022.01.02 |
---|---|
[C++] File I/O (ENG) (0) | 2022.01.02 |
[C++] New Concepts (ENG) (0) | 2021.12.05 |
[C++] Input (ENG) (0) | 2021.12.05 |
[C++] Output (ENG) (0) | 2021.12.05 |
댓글