Hai there…
I have trouble 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 the rest of the characters. I don’t 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";
}
1 Like
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 behaviour. 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;
}
Can you just specify the header files for the program.
Hi @syntax_error
You don’t need any header file other than #include<iostream>
for the code suggested by @EEngineer