problem whit strlen | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

problem whit strlen

i want the number of character in one string (string c) insert by input but it show error in the first parameter const * char and i understand it

3rd Jul 2017, 4:52 PM
matteo
matteo - avatar
8 Answers
+ 1
There are a few problems with your code. First you have the wrong include, then you have type compatibility issues string to char * . The code below will give you the expected result: #include <iostream> #include <cstring> using namespace std; int main(){ string c; int x; cout << "insert phrase\n"; cin >> c; x = strlen(c.c_str()); cout << x; } Or. Using gets, but the code playground doesn't seem to like this. #include <iostream> #include <cstring> #include <cstdio> using namespace std; int main(){ char * c; int x; cout << "insert phrase\n"; gets(c); x = strlen(c); cout << x; } Or better yet using string the right way #include <iostream> using namespace std; int main(){ string c; int x; cout << "insert phrase\n"; cin >> c; x = c.length(); cout << x; }
3rd Jul 2017, 5:19 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
No need to use strlen unless it's a char/wchar pointer. Just use the length member function. MyString.length();
3rd Jul 2017, 6:22 PM
aklex
aklex - avatar
+ 2
why don't you use sizeof operator
3rd Jul 2017, 4:59 PM
‎ ‏‏‎Anonymous Guy
+ 1
Can you post the code pliz ?
3rd Jul 2017, 4:56 PM
Jojo
+ 1
#include <iostream> #include <string.h> using namespace std; int main(){ string c; int x; cout << "insert phrase\n"; gets(c); x = strlen(c); cout << x; }
3rd Jul 2017, 5:03 PM
matteo
matteo - avatar
+ 1
why don't you use sizeof operator how i use it, i am a benniger
3rd Jul 2017, 5:04 PM
matteo
matteo - avatar
+ 1
@ aklex lol I was gonna post that as well in my previous post, but I got an important phone call and had to cut my post short. @matteo Also the playground doesn't seem to like the gets() function for input, even with the correct header. This is why I used cin >> c.
3rd Jul 2017, 6:28 PM
ChaoticDawg
ChaoticDawg - avatar
0
thanks
3rd Jul 2017, 9:02 PM
matteo
matteo - avatar