How to find the length of the string?

1
2
3
4
5
6
int t;
string a;
cin>>t;
getline(cin,a);
int len=a.length();
cout<<a<<" "<<len;

Input:
5 hello hi

Output:
<space>hellohi 0

why is the length 0?what can I do to get the correct length of the input string?
Last edited on
When I compile and run the code I get the following output: hello hi 9
I... don't know. Perhaps its because you are using an int. Maybe using a stringstream would fix it( convert t to a string). It is defined in the header <sstream>. I suggest you read up on that
if you want to find the length of the string, try
 
int l=strlen(stringname);

with the header file
#include<string.h>
OP's code is fine and runs normally as he would expect:

Input:
5 hello hi

Output:
hello hi 9

See for yourself:
http://ideone.com/SRmIQa


@OP: If you are getting different output you must not be running the code you think you are.
@George Kuriakose is right.

But, since you are using C++, use the header:

#include <cstring>

Hope this helped :)
Topic archived. No new replies allowed.