String library functions


Содержание

Diplom Consult.ru

Arrays and Strings

Some String Library Functions

C++ supports a wide range of string-manipulation functions. The most common are

strcpy( ) strcat( ) strlen( ) strcmp( )

The string functions all use the same header, . Let’s take a look at these functions now.

strcpy

A call to strcpy( ) takes this general form:

The strcpy( ) function copies the contents of the string from into to . Remember, the array that forms to must be large enough to hold the string contained in from. If it isn’t, the to array will be overrun, which will probably crash your program.

The following program will copy «hello» into string str :

#include #include using namespace std;

strcpy(str, «hello»); cout strcat( ) takes this form:

The strcat( ) function appends s2 to the end of s1 ; s2 is unchanged. Both strings must be null-terminated, and the result is null-terminated. For example, the following program will print hello there on the screen:

#include #include using namespace std;

C++ from the Ground Up

strcpy(s1, «hello»); strcpy(s2, » there»); strcat(s1, s2);

cout strcmp( ) takes this general form:

The strcmp( ) function compares two strings and returns 0 if they are equal. If s1 is greater than s2 lexicographically (i.e., according to dictionary order), then a positive number is returned; if it is less than s2, a negative number is returned.

The password( ) function, shown in the following program, is a password-verification routine. It uses strcmp( ) to check a user’s input against a password.

#include #include #include using namespace std;

if(password()) cout strcmp( ) is to remember that it returns false when the strings match. Therefore, you will need to use the ! (NOT) operator if you want something to occur when the strings are equal. For example, the following program continues to request input until the user types the word «quit»:

#include using namespace std;

cout strlen( ) is

where s is a string. The strlen( ) function returns the length of the string pointed to by s.

The following program will print the length of a string entered from the keyboard:

#include #include #include using namespace std;

cout 8 . The null terminator is not counted by strlen( ) .

When the following program is run, the string entered at the keyboard is printed in reverse. For example, «hello» will be displayed as olleh . Remember that strings are simply character arrays; thus each character can be referenced individually.

// Print a string backwards. #include

#include #include using namespace std;

char str[80]; int i;

cout =0; i—) cout #include #include using namespace std;

C string library function memcpy( )

In this article, you will learn about C string library function memcpy( ) that is related to memory with step by step explanation and example.

Since memcpy( ) is the standard library function defined in string.h header file, we should include string library before using it.

Function prototype of C string library function memcpy( )

str1 = Pointer to the destination array or object where content will be copied


str2 = Pointer to the source array or object from where content will be copied

n = size of content to be copied in bytes

This C string library function memcpy( ) copies n characters from the block of memory pointed by str1 to str2 .

It returns a pointer to the block of memory or object where contents are copied.

Note: The pointers are declared as void * so that they can be used for any data type.

This function does not check for terminating null character ‘\0’.

If you want to copy the characters in a same part of memory then we should use another string library function memmove( ) because the result of memcpy( ) is undefined in such cases.

C program to demonstrate the use of string library function memcpy( )

Output

Explanation

In the above program, we have used two standard string function memcpy( ) and strlen( ) .

strlen( ) is used to determine the length of str2 .

String in C (Standard Library Functions) – Part 4

In the last tutorial I gave a brief introduction of the relation between strings and pointers. I also told you about the 2D array of characters. Today I will tell you about some commonly used standard library string functions. These functions are made by the compiler vendors to speed up the manipulation of strings in C programming. So lets get started.

Standard Library String Functions

There are more than 18 standard library string function but only 4 of them are used very frequently. So I will only discuss those 4 functions which are strlen(), strcpy(), strcat(), strcmp().

Note: The header file that we will use for these functions is string.h.

strlen() in C

As its name suggest, this function is made to calculate the length of the string. By using this function we can calculate the number of characters in any string.

Strings library

Language
Standard Library Headers
Freestanding and hosted implementations
Named requirements
Language support library
Concepts library (C++20)
Diagnostics library
Utilities library
Strings library
Containers library
Iterators library
Ranges library (C++20)
Algorithms library
Numerics library
Input/output library
Localizations library
Regular expressions library (C++11)
Atomic operations library (C++11)
Thread support library (C++11)
Filesystem library (C++17)
Technical Specifications

The C++ strings library includes support for three general types of strings:

  • std::basic_string — a templated >std::basic_string_view (C++17) — a lightweight non-owning read-only view into a subsequence of a string.
  • Null-terminated strings — arrays of characters terminated by a special null character.
Null-terminated strings
Byte strings
Multibyte strings
Wide strings
Classes

Contents

[edit] std::basic_string

The templated >std::basic_string generalizes how sequences of characters are manipulated and stored. String creation, manipulation, and destruction are all handled by a convenient set of class methods and related functions.

Several specializations of std::basic_string are provided for commonly-used types:

Type Definition
std::string std:: basic_string char >
std::wstring std:: basic_string wchar_t >
std::u8string (since C++20) std:: basic_string char8_t >
std::u16string (since C++11) std:: basic_string char16_t >
std::u32string (since C++11) std:: basic_string char32_t >

std::basic_string_view

Several specializations of std::basic_string_view are provided for commonly-used types:

Type Definition
std::string_view (since C++17) std:: basic_string_view char >
std::wstring_view (since C++17) std:: basic_string_view wchar_t >
std::u8string_view (since C++20) std:: basic_string_view char8_t >
std::u16string_view (since C++17) std:: basic_string_view char16_t >
std::u32string_view (since C++17) std:: basic_string_view char32_t >
(since C++17)

[edit] Null-terminated strings

Null-terminated strings are arrays of characters that are terminated by a special null character. C++ provides functions to create, inspect, and modify null-terminated strings.

There are three types of null-terminated strings:


[edit] std::char_traits

The string library also prov >std::char_traits that defines types and functions for std::basic_string and std::basic_string_view (since C++17) . The following specializations are defined:

[edit] Conversions and classification

The localizations library prov > std:: wstring_convert or std :: toupper ) as well as functions that > std :: isspace or std :: isdigit ).

C – Strings and String functions with examples

By Chaitanya Singh | Filed Under: c-programming

String is an array of characters. In this guide, we learn how to declare strings, how to work with strings in C programming and how to use the pre-defined string handling functions.

We will see how to compare two strings, concatenate strings, copy one string to another & perform various string manipulation operations. We can perform such operations using the pre-defined functions of “string.h” header file. In order to use these string functions you must include string.h file in your C program.

Илон Маск рекомендует:  Статьи о MySQL языке баз данных

String Declaration

Method 1:

Method 2: The above string can also be defined as

In the above declaration NULL character (\0) will automatically be inserted at the end of the string.

What is NULL Char “\0”?
‘\0’ represents the end of the string. It is also referred as String terminator & Null Character.

String I/O in C programming

Read & write Strings in C using Printf() and Scanf() functions

Note: %s format specifier is used for strings input/output

Read & Write Strings in C using gets() and puts() functions

C – String functions

C String function – strlen

size_t represents unsigned short
It returns the length of the string without including end character (terminating char ‘\0’).

Example of strlen:

strlen vs sizeof
strlen returns you the length of the string stored in array, however sizeof returns the total allocated size assigned to the array. So if I consider the above example again then the following statements would return the below values.

strlen(str1) returned value 13.
sizeof(str1) would return value 20 as the array size is 20 (see the first statement in main function).

C String function – strnlen

size_t represents unsigned short
It returns length of the string if it is less than the value specified for maxlen (maximum length) otherwise it returns maxlen value.

Example of strnlen:

Output:
Length of string str1 when maxlen is 30: 13
Length of string str1 when maxlen is 10: 10

Have you noticed the output of second printf statement, even though the string length was 13 it returned only 10 because the maxlen was 10.

C String function – strcmp

It compares the two strings and returns an integer value. If both the strings are same (equal) then this function would return 0 otherwise it may return a negative or positive value based on the comparison.

If string1 string2 then it would return positive value.
If string1 == string2 then you would get 0(zero) when you use this function for compare strings.

Example of strcmp:

Output:

C String function – strncmp

size_t is for unassigned short
It compares both the string till n characters or in other words it compares first n characters of both the strings.

Example of strncmp:


Output:

C String function – strcat

It concatenates two strings and returns the concatenated string.

Example of strcat:

Output:

C String function – strncat

It concatenates n characters of str2 to string str1. A terminator char (‘\0’) will always be appended at the end of the concatenated string.

Example of strncat:

Output:

C String function – strcpy

It copies the string str2 into string str1, including the end character (terminator char ‘\0’).

Example of strcpy:

Output:

C String function – strncpy

char *strncpy( char *str1, char *str2, size_t n)
size_t is unassigned short and n is a number.
Case1: If length of str2 > n then it just copies first n characters of str2 into str1.
Case2: If length of str2

String Library Functions

There are 16 string functions included in the String library, allowing you to do everything from counting the elements in an array to finding and replacing all occurances of substrings. I’ve included full descriptions here only of the functions used in my examples. For a complete listing of the functions, see the WMLScript Standard Libraries Specification and start reading on page 23.

  • elementAt
  • Syntax: String.elementAt(string, index, separator);

Returns the indexth element of the array string, where each element in the array is separated by separator.

  • replaceAt
  • Syntax: String.replaceAt(string, index, separator);

Returns the indexth element of the array string, where each element in the array is separated by separator.

  • format
  • Syntax: String.format(format, value);

Converts value to a string with format specified by format. format has the form:

C Library String Functions

You can access the builtin C library functions through header files. The string related functions are located in String.h file.

Each function listed below has a specific purpose.

strlen()
To find the length of a string.
strlwr() Converts a string to lowercase.
strupr() Converts a string to uppercase.
strcat() Add one string to another to make a bigger string.
strncat() Add n character of a string to another string
strcpy() Copies a string to another string replaces any existing.
strcmp() Compare two strings.
strncpy() Copies first n characters of two strings.
strncmp() Compares only first n characters with another string.
stricmp() Compare two strings, disregards case.
strcmpi() Same as stricmp()
strncmp() Compares first n characters of two strings.
strnicmp() Compares first n characters of two strings, disregards case
strdup() Duplicate a string.
strchr() Finds first occurrence of a given character in a string.
strrchr() Finds last occurrence of a given character in a string.
strstr() Finds first occurrence of a given string in another string.
strset() Changes all characters of a string to given character.
strnset() Changes first n char of a string to given character.
strrev() Reverse a given string.

From the above table, strlen(), strcpy(), strcmp() and strcat() are the most frequently used functions.

C Library String Functions Example

You will write a program that implement these 4 builtin functions.

functions

  • 11/04/2020
  • 11 minutes to read

    • +1
getline stod stof
stoi stol stold
stoll stoul stoull
swap to_string to_wstring

getline

Extract strings from the input stream line-by-line.

Parameters

is
The input stream from which a string is to be extracted.

str
The string into which are read the characters from the input stream.

delim
The line delimiter.

Return Value

The input stream is.

Remarks

The pair of function signatures marked (1) extract characters from is until delim is found, storing them in str.

The pair of function signatures marked (2) use newline as the default line delimiter and behave as getline( is , str , is . widen (‘ \n ‘)).

The second function of each pair is an analog to the first one to support rvalue references.

Extraction stops when one of the following occurs:

At end-of-file, in which case the internal state flag of is is set to ios_base::eofbit .

After the function extracts an element that compares equal to delim , in which case the element is neither put back nor appended to the controlled sequence.

After the function extracts str. max_size elements, in which case the internal state flag of is is set to ios_base::failbit .

Some other error other than those previously listed, in which case the internal state flag of is is set to ios_base::badbit

For information about internal state flags, see ios_base::iostate.

If the function extracts no elements, the internal state flag of is is set to ios_base::failbit . In any case, getline returns is.

If an exception is thrown, is and str are left in a valid state.

Example

The following code demonstrates getline() in two modes: first with the default delimiter (newline) and second with a whitespace as delimiter. The end-of-file character (CTRL-Z on the keyboard) is used to control termination of the while loops. This sets the internal state flag of cin to eofbit , which must be cleared with basic_ios::clear() before the second while loop will work properly.

Converts a character sequence to a double.

Parameters

Parameter Description
str The character sequence to be converted.
idx The index value of the first unconverted character.

Return Value

The double value.

Remarks

The function converts the sequence of elements in str to a value val of type double as if by calling strtod( str.c_str(), _Eptr) , where _Eptr is an object internal to the function. If str.c_str() == *_Eptr it throws an object of type invalid_argument . If such a call would set errno , it throws an object of type out_of_range . Otherwise, if idx is not a null pointer, the function stores *_Eptr — str.c_str() in *idx and returns val .

Converts a character sequence to a float.

Parameters

Parameter Description
str The character sequence to be converted.
idx The index value of the first unconverted character.


Return Value

The float value.

Remarks

The function converts the sequence of elements in str to a value val of type float as if by calling strtof( str.c_str(), _Eptr) , where _Eptr is an object internal to the function. If str.c_str() == *_Eptr it throws an object of type invalid_argument . If such a call would set errno , it throws an object of type out_of_range . Otherwise, if idx is not a null pointer, the function stores *_Eptr — str.c_str() in *idx and returns val .

Converts a character sequence to an integer.

Return Value

The integer value.

Parameters

Parameter Description
str The character sequence to be converted.
idx Contains the index of the first unconverted character on return.
base The number base to use.

Remarks

The function stoi converts the sequence of characters in str to a value of type int and returns the value. For example, when passed a character sequence «10», the value returned by stoi is the integer 10.

stoi behaves similarly to the function strtol for single-byte characters when it is called in the manner strtol( str.c_str(), _Eptr, idx) , where _Eptr is an object internal to the function; or wcstol for wide characters, when it is called in similar manner, wcstol(Str.c_str(), _Eptr, idx) . For more information, see strtol, wcstol, _strtol_l, _wcstol_l.

If str.c_str() == *_Eptr , stoi throws an object of type invalid_argument . If such a call would set errno , or if the returned value cannot be represented as an object of type int, it throws an object of type out_of_range . Otherwise, if idx is not a null pointer, the function stores *_Eptr — str.c_str() in *idx .

Converts a character sequence to a long.

Parameters

Parameter Description
str The character sequence to be converted.
idx The index value of the first unconverted character.
base The number base to use.

Return Value

The long-integer value.

Remarks

The function converts the sequence of elements in str to a value val of type long as if by calling strtol( str.c_str(), _Eptr, idx) , where _Eptr is an object internal to the function. If str.c_str() == *_Eptr it throws an object of type invalid_argument . If such a call would set errno , it throws an object of type out_of_range . Otherwise, if idx is not a null pointer, the function stores *_Eptr — str.c_str() in *idx and returns val .

stold

Converts a character sequence to a long double.

Parameters

Parameter Description
str The character sequence to be converted.
idx The index value of the first unconverted character.

Return Value

The long double value.

Remarks

The function converts the sequence of elements in str to a value val of type long double as if by calling strtold( str.c_str(), _Eptr) , where _Eptr is an object internal to the function. If str.c_str() == *_Eptr it throws an object of type invalid_argument . If such a call would set errno , it throws an object of type out_of_range . Otherwise, if idx is not a null pointer, the function stores *_Eptr — str.c_str() in *idx and returns val .

stoll

Converts a character sequence to a long long.

Parameters

Parameter Description
str The character sequence to be converted.
idx The index value of the first unconverted character.
base The number base to use.

Return Value

The long long value.

Remarks

The function converts the sequence of elements in str to a value val of type long long as if by calling strtoll( str.c_str(), _Eptr, idx) , where _Eptr is an object internal to the function. If str.c_str() == *_Eptr it throws an object of type invalid_argument . If such a call would set errno , it throws an object of type out_of_range . Otherwise, if idx is not a null pointer, the function stores *_Eptr — str.c_str() in *idx and returns val .


stoul

Converts a character sequence to an unsigned long.

Parameters

Parameter Description
str The character sequence to be converted.
idx The index value of the first unconverted character.
base The number base to use.

Return Value

The unsigned long-integer value.

Remarks

The function converts the sequence of elements in str to a value val of type unsigned long as if by calling strtoul( str.c_str(), _Eptr, idx) , where _Eptr is an object internal to the function. If str.c_str() == *_Eptr it throws an object of type invalid_argument . If such a call would set errno , it throws an object of type out_of_range . Otherwise, if idx is not a null pointer, the function stores *_Eptr — str.c_str() in *idx and returns val .

stoull

Converts a character sequence to an unsigned long long.

Parameters

Parameter Description
str The character sequence to be converted.
idx The index value of the first unconverted character.
base The number base to use.

Return Value

The unsigned long long value.

Remarks

The function converts the sequence of elements in str to a value val of type unsigned long long as if by calling strtoull( str.c_str(), _Eptr, idx) , where _Eptr is an object internal to the function. If str.c_str() == *_Eptr it throws an object of type invalid_argument . If such a call would set errno , it throws an object of type out_of_range . Otherwise, if idx is not a null pointer, the function stores *_Eptr — str.c_str() in *idx and returns val .

Exchanges the arrays of characters of two strings.

Parameters

left
One string whose elements are to be swapped with those of another string.

right
The other string whose elements are to be swapped with the first string.

Remarks

The template function executes the specialized member function left.swap(right) for strings, which guarantees constant complexity.

Example

to_string

Converts a value to a string .

Parameters

Parameter Description
Val The value to be converted.

Return Value

The string that represents the value.

Remarks

The function converts Val to a sequence of elements stored in an array object Buf internal to the function as if by calling sprintf(Buf, Fmt, Val) , where Fmt is

«%d» if Val has type int

«%u» if Val has type unsigned int

«%ld» if Val has type long

«%lu» if Val has type unsigned long

«%lld» if Val has type long long

«%llu» if Val has type unsigned long long


«%f» if Val has type float or double

«%Lf» if Val has type long double

The function returns string(Buf) .

to_wstring

Converts a value to a wide string.

Parameters

Parameter Description
Val The value to be converted.

Return Value

The wide string that represents the value.

Remarks

The function converts Val to a sequence of elements stored in an array object Buf internal to the function as if by calling swprintf(Buf, Len, Fmt, Val) , where Fmt is

L»%d» if Val has type int

L»%u» if Val has type unsigned int

L»%ld» if Val has type long

L»%lu» if Val has type unsigned long

L»%lld» if Val has type long long

L»%llu» if Val has type unsigned long long

L»%f» if Val has type float or double

L»%Lf» if Val has type long double

String library functions

toupper() doesn’t change its parameter, and it returns the uppercase letter.
It returns int for. historical reasons. and you may safely cast it back to char.

You call the function toupper() but don’t do anything with the result.
You should assign the result to something, like this:
array[i] = toupper(array[i]);

Other points. On line 14, SIZE should be a constant.
(the value is also a bit miserly, there are many words of more than 9 letters).
const int SIZE = 50;
Standard C++ requires that the array on line 15 is specified using a constant, hence the use of const on line 14.

As @Catfish2 pointed out toupper does not change its parameter. You shall use its return value to change the original character

C++ Programming Language

Characters and Strings

Characters

Header — Character Type Library

The character type header (ported from C’ ), contains the following character handling functions.

FUNCTION EXAMPLE

All these functions treat a char as a signed int .

Strings: The C-String and the string class

Recall that C++ supports two types of strings:

  1. The C-style string (or C-String) in header cstring (ported over from C’s string.h ), which represents a string as a char array terminated by a null character ‘\0’ (or 0) (null-terminated char array).
  2. The new C++ string class in header string . string is a regular class, with public interface defined in the constructors and public member functions.

C-String Literals


A string literal such as «hello» is treated as «an array of n const char «, terminated with the null ‘\0’ character (equivalent to 0), where n is the length of the array including the terminating null character.

Take note that you cannot modify the content pointed to by const char * .

C-String Headers and Functions

C-string (null-terminated char array) can be declared as char* or char[] . This is because C treats an array name as a pointer to the first element of the array. Unlike regular arrays, there is no need to pass the length of C-string into function, as the function can deduce the length from the terminating null character.

C-String Functions in header

The header (ported from C’s string.h ) contains these commonly-used functions to operate on C-strings.

FUNCTION EXAMPLE
C-String Functions in header

The header (ported from C’s ) contains functions to convert C-strings to fundamental types.

FUNCTION EXAMPLE
C-String Input/Output Functions in Header

The supports these functions for c-string input and output:

FUNCTION EXAMPLE
Converting C-string to Uppercase/Lowercase

You probably have to write your own function using cctype ‘s toupper() and tolower() , which converts individual character. For example,

The C++’s string class

The string class, in header and under namespace std (i.e., std::string ), models character sequences. The string class is an instantiation of the basic_string template class that uses char type with a typedef .

string Class Constructors

You cannot construct a string from char , int or double .

Example: string Constructor
Example: C++11 string Constructor
string Class Overloaded Operators

Most of the string class operators are overloaded to handle string objects, as well as C-string and literals.

Public Functions

Most of the string class functions are overloaded to handle string objects, as well as C-string and literals.

Unlike C-string, which uses a fixed-size array, the string class handles the memory allocated implicitly. In other words, you can append more characters without worrying about exceeding the size. C++ implementation may allocate an initial block which is larger than the actual string length to allow the content to grow, and allocate more block when the current block is filled. You can use function capacity() to check the current allocation, and reserve() to request for a minimum allocation.

Some functions, such as ofstream ‘s open() which opens a file, accept only C-string. You can use c_str to get a C-string from an string object.

Example: string objects and their operations

[TODO] More Example

Converting a string to Uppercase/Lowercase

Use the transform() function in algorithm .

The C-String Input Methods

C-string has three input methods: stream extraction operator ( >> ), getline() and get() . All 3 functions belong to the istream class.

istream ‘s Overloaded Stream Extraction Operator ( >> )

The stream extraction operator ( >> ) of istream class has the following prototype for C-strings:

It extracts characters from the input stream and store into str , until either a whitespace (blank, tab, newline) is encountered or width-1 characters is read. A terminating null character is automatically inserted. The default width is 0, indicating unlimited. You can set the width via cin >> setw(n) (in header ) or cin.width(n) . setw() is non-sticky and is only applicable to next input operation. It is reset to 0. The trailing whitespace is left in the input stream. The leading white spaces are ignored.


We set the width to the SIZE (=5) of the char[] . cin reads up to 4 characters or whitespace.

  • If you enter «12\n» , «12» is read into str , and «\n» remains in the input buffer.
  • If you enter «12345\n» , «1234» is read into str , and «5\n» remains in the input buffer.
  • If you enter «12 345\n» , «12» is read into str , and » 345\n» remains in the input buffer.
  • The next cin >> discards the leading whitespaces and starts with the first non-whitespace character.
  • If width is not set properly and if the input (including the terminating null character) exceeds the size of char array, memory will be corrupted.
  • You may need to flush the input buffer (see below).
istream::getline()

The getline() function of the istream class has the following prototypes:

getline() extracts characters from the input stream and stores in str , until either it reaches the delimiter character (default of ‘\n’ ), or n-1 character is written to str . A terminating null character is automatically inserted. The delimiter, if found, is extracted and discarded from input stream. You can use cin.gcount() to get the number of characters extracted (including delim ). getline() reads all whitespace (including leading whitespaces which is ignore by cin >> ).

If n-1 character is read and the next character is not delimit, then the failbit (of the istream ) is set. You can check the failbit via bool function cin.fail() . You need to invoke cin.clear() to clear the error bit. Otherwise, all subsequent getline() will fail and return gcount() of 0.

Again, we set n to the SIZE (=5) of char[] . getline() reads up to 4 characters or ‘\n’ .

  • If you enter «xxxx\n» , where xxxx may include whitespaces, «xxxx» is read into str , and «\n» discarded from input buffer.
  • If you enter «xxxxyyy\n» , «xxxx» is read into str, «yyy\n» remains in input buffer. failbit is set. You need to clear the error bits before issuing another getline() call.
istream::get()

The get() function of the istream class has the following prototypes for C-string:

get(str, n, delim) is similar to getline(str, n, delim) , except that the delim character is not extracted and remains in the input stream.

Single-character Input

The get() member function is more often used to read a single character, unformatted, including whitespaces and newlines. It has the following two versions:

When the end-of-file is encountered, get(char &) returns a null pointer, which is converted to false . On the other hand, get(void) return a special value EOF (defined in ). get(char &) has no room to represent any special symbol such as EOF!

In brief, there are 3 methods for reading single character, cin >> char , get(char &) and get(void) . cin >> char skips whitespaces, get(char &) reads a character by reference, while get(void) reads a character and return an int . get(void) is closely resembled the C’s getchar(void) function (in stdio.h ) and can be used to convert C programs into C++.

Flushing the cin Buffer

Use cin.ignore() as follows. You may need to issue an cin.clear() to clear the error bits first.

Others

istream::peek() , istream::unget() , etc.

The string Class Input Methods

The string class has two input methods: stream extraction operator ( >> ) and getline() . Both methods are similar to C-string counterpart, but they are much simpler, as you don’t need to worry about the limit of the string , compared with a fixed-size char array.

string ‘s Stream Extraction Operator ( >> )

The string class overloads the >> (stream extraction operator) via friend function such that it operates on string object like C-string:

It extracts a string (word) from the input stream, delimited by whitespace (blank, tab or newline), and stores in str , overriding its previous value. The size of str is determined by the length of input.

string::getline()

The string class also provides a friend function getline() :

It extracts characters from the input stream into str until the delimiter character is found (default of newline ‘\n’ ) or end-of-file is reached. The delimiter is extracted and discard from the input buffer, i.e., the next operation will begin after the delimiter. The size of str is determined by the length of input.

Notes
  • The maximum allowable size for a string object is defined by the constant string::npos , which is typically the maximum value of unsigned int .
  • If getline() is used to read from a file, and end-of-file is encountered, the eofbit of the input stream will be set. That is, fail() and eof() of the input stream will return true .
  • If the maximum allowable size of string is reached, or memory exhausted, the failbit of the input stream will be set. That is, fail() of the input stream will return true .
  • An input stream maintains its status in these bits: goodbit ( good() function) indicates all is fine; failbit ( fail() function) indicates input error; badbit ( bad() function) indicates recognized failure such as hardware failure; eofbit ( eof() function) indicates end-of-file detected.

basic_string Template Class

The string class is an instantiation of the basic_string template class with parameterized type of char .

The declaration of basic_string is:

There are 4 instantiations for basic_string template class, with a typedef .

Unicode Characters and Strings

[TODO] Types: wchar_t , char16_t , char32_t .

[TODO] C’s headers: cuchar , wchar , cwctype .

[TODO] C++ Classes: wstring , u16string , u32string .

Latest version tested: GCC 4.6.2
Last modified: May, 2013

Илон Маск рекомендует:  Что такое код ora_columnsize
Понравилась статья? Поделиться с друзьями:
Кодинг, CSS и SQL