Easy tutorial for C / C ++ - string 2
('>>' operator, cin.get(), strlen() functions)
strlen()
:
- A function to determine the length of a string. To use
the strlen () function, you need to include the string.h header file. That is,
you need to write #include <string.h> in your code.
- Let's look at an example that takes the length of a
string input through cin. To get a string, we use the '>>' operator of
the cin object and the 'get ()' method to see the difference.
Example Code
#include
<iostream>
#include
<string.h>
using
namespace std;
int
main() {
char Tst_1[255] ;
char Tst_2[255] ;
int LenS ;
cout << "Using \'>>\'
operator" << endl ;
cout << "Enter a string. :
" ;
cin >> Tst_1 ;
LenS = strlen(Tst_1);
cout << " Tst_1 = " << Tst_1 << endl
;
cout << " strlen(Tst_1) = "
<< LenS << endl ;
cout << endl ;
cin.ignore(255,'\n');
cout << "Using \'cin.get()\'
method" << endl ;
cout << "Enter a string. :
" ;
cin.get(Tst_2,255) ;
LenS = strlen(Tst_2);
cout << " Tst_2 = " << Tst_2 << endl
;
cout << " strlen(Tst_2) = "
<< LenS << endl ;
cin.ignore(255,'\n');
return 0;
}
- String arrays 'Tst_1' and 'Tst_2' were defined to store
the string. And we declared an integer variable 'LenS' to store the length of
the string.
- First, we wrote the code for receiving input using
'>>' operator. After input, we will assign the length of the input string
to 'LenS'. We will then print the contents and length of the string.
- To empty the string stored in the buffer, we use the
command 'cin.ignore (255,' \ n ');' And thus the next data can be read from the
keyboard.
- We have written the code for receiving input using
'cin.get ()' method. We will then input the string and print the contents and
length of the string.
results
:
Using
'>>' operator
Enter
a string. :
- You will be prompted to enter a string. Type "abcd
efgh" and hit enter.
Using
'>>' operator
Enter
a string. : abcd efgh
Tst_1
= abcd
strlen(Tst_1) = 4
Using
'cin.get()' method
Enter
a string. :
- As a result, only "abcd" is output and the
length of the string is '4'. If you use the '>>' operator to input
characters with the space character, this space character is regared as the end
of the string. And the characters after it are not stored in the variable.
Therefore, only the "abcd" will be saved and the length will be 4.
- In the input method using 'cin.get ()' method, input
"abcd efgh" and press enter.
Using
'>>' operator
Enter
a string. : abcd efgh
Tst_1
= abcd
strlen(Tst_1) = 4
Using
'cin.get()' method
Enter
a string. : abcd efgh
Tst_2
= abcd efgh
strlen(Tst_2) = 9
- You can
see that the input "abcd efgh" is correctly printed. And the length
of the string is 9. (Including the space bar)
No comments:
Post a Comment