Problem in reading a string and printing its length


#1

Hai there…
I have trouble in finding the error in a program written in c++. The program simply inputs a string
to find the length of the same.But when I enter a string data, the str array only gets first 3 characters of the string. It omits rest of the characters. I dont know why this happens. Need some help.The program is given below.

#include<iostream>
using namespace std;
int main()
{	int length=0;
	char str[10];
	cout<<"Enter a string"<<"\n";

	for(int i=0; str[i] != '\0'; i++)
	cin>>str[i];

	for(int i=0; str[i]!='\0'; i++)
	{
		cout<<str[i];
		length++;
	}
	cout<<"\n"<<"Length of the string="<<""<<length<<"\n";
}

#2

Hi, In your program the char str[10] is uninitialized character array which means the array is somewhere in memory with an indeterminate value. In the first for loop you are trying to check '\0' in str[i] without initializing it will cause an undefined behavior. You have assumed that the array is terminated by '\0', which may or may not be true since its an uninitialized array.
I suggest you to use the string variable and length() function in your code.

int main()
{
    string str;
    cout<<"Enter the string"<<"\n";
    cin >> str;
    cout << str << endl;
    cout << "Length = " << str.length() << endl;
}

#3

Can you just specify the header files for the program.


#4

Hi @syntax_error
You don’t need any header file other than #include<iostream> for the code suggested by @EEngineer