bytes returned by string.length()

I have to ask two things about string.length()

1)
I am getting a string input from user and than trying it to calculate string.length()

In the following link
http://www.cplusplus.com/reference/string/string/length/

it says that string.length() returns "number of bytes". However, for a char input of "abc" it returns 3. I assume that each character takes 1 byte(8 bits). Now for integer input in string, "123" the output of string.length is still 3. Now i don't know how to check the bits for int in my system but its usually 16 bits(2 bytes). So my question is how do i get 3 as string length each time??


1
2
3
4
5
6
    string inputString;  
    cout << "Enter a string" << endl;
    getline (cin, inputString);
    
    const unsigned int length_of_Input_string = inputString.length() ;



OR using size_t

1
2
3
4
5
6

    size_t length_of_Input_string = inputString.length() ;
    
    const unsigned int length_of_Input_string = inputString.length() ;

    cout << "String length is :" << length_of_Input_string << endl;


2)
I have to further compare string.length with "1" to check
if (string length >= 1 )

Since the return type of string.length() is size_t , I am doing it the following way:

1
2
3
4
5
6
7
8

    size_t one = 1;

    if( length_of_Input_string <= one )
    {
         //Some Code
    }


Is using size_t for a value of "1" fine? I mean usually 'int' is used but it will cause contrast type comparison here. Is it normal/efficient to do it like above or is there another way around?
it says that string.length() returns "number of bytes".

You would be better off thinking in terms of number characters instead of bytes, IMO.

Now for integer input in string, "123" the output of string.length is still 3. Now i don't know how to check the bits for int in my system but its usually 16 bits(2 bytes). So my question is how do i get 3 as string length each time??

Because if you're dealing with a string the string "123" contains the three digit characters, '1', '2', and '3' not the number 123. There is a difference between characters and numbers in C++.

Also in this snippet:
const unsigned int length_of_Input_string = inputString.length() ;
You really should be using a size_t rather than the unsigned int. The std::string.length() function returns a size_t which may not be the same as an unsigned int, it could be an unsigned long or some other unsigned type.

I have to further compare string.length with "1"

You can't compare the length of the string to a "1" because "1" is a string not a number. But you can compare the length of the string to 1. For example to check if the string contains some characters you can use:
1
2
3
4
5
if (some_string.length() > 0)
   // Do something.
// Or just use the empty() function instead.
if(some_string.empty())
   // Do something. 


Topic archived. No new replies allowed.