We have some word, that we should identify the length of. How can I do that? Example INPUT: "hello" - without quotes; Example OUTPUT: 5
Asked
Active
Viewed 901 times
-2
-
http://www.cplusplus.com/reference/string/string/length/ – Daniel Nudelman Jan 05 '21 at 12:17
-
The answer in this case is simply to search, which doesn't make for a good question on SO. – underscore_d Jan 05 '21 at 12:20
-
1Things like this should be covered in any [decent C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Or you could do a quick search on the internet "C++ get length of string". – Lukas-T Jan 05 '21 at 12:21
-
Does this answer your question? [How to get the number of characters in a std::string?](https://stackoverflow.com/questions/905355/how-to-get-the-number-of-characters-in-a-stdstring) – NotAProgrammer Jan 05 '21 at 12:32
4 Answers
2
If input is contained in a std::string you can find the length as stated by Ravi. If it's a C string you find the length with
int len = strlen(INPUT);
In C/C++ upper case is normally used for constants so it's better to name the string input, not INPUT.

StureS
- 227
- 2
- 10
1
string str;
cin>>str;
//use this
cout<<str.length();
//or use this
cout<<str.size();
both of them will work fine.

Azahar Alam
- 708
- 5
- 16
0
There is one function to find length in C++. You can try by using:
input.length()
Also remember, you need to include:
#include <iostream>
using namespace std;
Refer this document : https://www.w3schools.com/cpp/cpp_strings_length.asp

Ravi Khunt
- 262
- 2
- 8
-
1You don't need to inlcude iostream to use `std::string`. And you shouldn't use `using namespace std;`, it's [bad practice](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – Lukas-T Jan 05 '21 at 12:25
0
You can use input.length() or input.size()
.
Or you can use this simple loop.
for (i = 0; str[i]; i++)
;
cout << i << endl;

ColonelBobby
- 9
- 3
-
2Don't recommend newbies to roll their own version of standard functions. It it totally unnecessary. – underscore_d Jan 05 '21 at 12:32
-
2That loop does what `std::strlen` does, but `std::string` is allowed to contain additional null-characters, so it's different from `std::string::length`. – Lukas-T Jan 05 '21 at 12:40