Reputation: 3
I'm trying to get the length of the string from a char array
My input is:alpha kian namikian
and the output should be 5 4 8
but at the moment my output is 11 11 11 11 11 11 11 11 11 11 11
which is not what I'm trying to achieve.
int i,count;
char str[100];
cout<<"enter string\n";
for(i=0;;i++)
{
cin>>str[i];
if(cin.get()=='\n')
{
count=i+1;
break;
}
}
for(i=0;i<count;i++)
{
int len = strlen(str);
cout<<len<<"\n";
}
Upvotes: 0
Views: 77
Reputation: 184
You have a compilation error because you're trying to fit an array of strings as a parameter to strlen
. In your code, str
contains all the strings, so you have to use access operator []
just like you did when you were taking strings from standard input.
int len = strlen(str)
becomes int len = strlen(str[i])
and that should fix the error.
EDIT:
It looks like you can't use strlen
with strings. Use length()
instead.
int len = str[i].length()
EDIT #2:
Adding full code for reference with output:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i, count;
string str[100];
cout << "enter string\n";
for (i = 0;; i++)
{
cin >> str[i];
if (cin.get() == '\n')
{
count = i + 1;
break;
}
}
for (i = 0; i < count; i++)
{
int len = str[i].length();
cout << len << "\n";
}
}
Output:
enter string
alpha kian namikian
5
4
8
Upvotes: 1
Reputation: 308
You can use this approach using the vector
type string
and exit the storing of the strings if entered string is exit
I am using a temp
variable to store the string at any index and output the corresponding length.
int i;
vector<string> str;
cout << "Enter String\n";
while(cin)
{
string temp;
cin >> temp;
if(temp == "exit")
break;
else
str.push_back(temp);
}
int n= str.size();
for(i = 0; i< n; i++)
{
string temp = str[i];
int len = temp.length();
cout << len << endl;
}
Upvotes: 0