I wrote below program to find lenght of string...It works in the case only when i enter a string continous without any spaces between words example: Itiswonderful
I was thinking of such a logic where it can count the lenght when spaces are also there for E.g.
Program should be able to give output to this string with spaces "It is wonderful".
main()
{
int length;
char str1[30];
cout<<"Please enter string for which you want to find length"<<endl;
cin>>str1;
length=strlen(str1);
cout<<"Length of string entered"<<length<<endl;
system("PAUSE");
}
main()
{
string str1;
cout<<"Please enter string for which you want to find length"<<endl;
cin>>str1;
length=str1.size();
cout<<"Length of string entered"<<length<<endl;
system("PAUSE");
}
When you use operator >> it reads until a white space will be encountered. To read a sentence with blanks you should use function std::getline instead of operator >>
For example
1 2 3 4 5
char s[30];
std::cin.getline( s, sizeof( s ) );
std::cout << s << std::endl;
By the way you shall write
int main()
instead of
main()
Also you should include header <cstring> instead of <string>. And variable length shall be declared as size_t length; instead of int length;
int main() {
size_t length;
char str1[100],s[30];
cout<<"Please enter string for which you want to find length"<<endl;
cin>>str1;
std::cin.getline( s, sizeof( s ) );
std::cout << s << std::endl;
system("PAUSE");
}
I also tried solution by Nickul and get an error "15 J:\C++ Programs\StrLength.cpp request for member `size' in `str1', which is of non-class type `char[100]' "
"I also tried solution by Nickul and get an error "15 J:\C++ Programs\StrLength.cpp request for member `size' in `str1', which is of non-class type `char[100]' ""
You have to declare str1 as string for the .size() to work, as I mentioned in my first reply... you probably missed that
But, as vlad mentioned, you have to use cin.getline(str1, maximum size of s(enter a number here)) instead of cin, otherwise it won't read past the space.
So, it would be like this(without using the string class, as it does not work with cin.getline):
#include<string>
#include<iostream>
using namespace std;
int main()
{
char str1[100];
cout<<"Please enter string for which you want to find length"<<endl;
cin.getline(str1,100);
length=strlen(str1);
cout<<"Length of string entered"<<length<<endl;
system("PAUSE");
return 0;
}