Length of string

1
2
3
4
5
6
7
8
9
10
11
12
13
int main(){
	
	char *Statement = "Hello! How are you today? I am well, thankyou.";

	cout << sizeof(Statement) << endl;
	int j = 0;
	while( j < sizeof( Statement)){
		for( int i = 0; i < 3; i++){
			cout << *( Statement + i + j );
		}
		cout << endl;
		j++;
	}

Why does the program not recognise the size of Statement as more than the 1st 4 letter? The while loop doesn't go through the whole Statement just "Hello".
Last edited on
statement is a pointer.
sizeof(pointer) is 4.
You use std::strlen() or std::char_traits<char>::length() to determine the length of a string == number of characters not counting the terminating zero or any characters beyond in the string buffer.

If you want the total size of the array, you must either track that some way yourself or use std::extent<decltype(Statement)>::value if you still have access to the actual array.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
#include <type_traits>
int main()
{
  const char s[] = "Hello world!";
  std::cout << s << "\n";
  std::cout << std::char_traits <char> ::length( s ) << " characters\n";
  std::cout << std::extent <decltype(s)> ::value << " size\n";
}


BTW, pointers to string literals should be const.

Hope this helps.
Topic archived. No new replies allowed.