0

I want to calculate length of each string contained in string array without using length function.

Here's my code .I have intialized l to zero agian but output is still 5. #include <iostream> #include <string> using namespace std; int main() { string array[3]={"Talha","boss","miss"}; for (int i=0;i<3;i++) { string myvar=array[i]; int l=0; for (int j= 0; myvar[j] != '\0'; j++) { l++;} cout<<array[i]<<" of length is "<<l<<endl; int m=0; l=m; //after each iteration } return 0; }

21st Mar 2022, 5:44 PM
Muhammad Talha Atif
Muhammad Talha Atif - avatar
5 odpowiedzi
+ 1
your code seems good. Even on sololearn you will get the correct output. it must be some problem with your VS code #include <iostream> #include <string> using namespace std; int main() { string array[3]={"Talha","boss","miss"}; for (int i=0;i<3;i++) { string myvar=array[i]; int l=0; // when loop starts, j becomes 0 automatically for (int j= 0; myvar[j] != '\0'; j++) { l++;} cout<<array[i]<<" of length is "<<l<<endl; l=0; //after each iteration } return 0; }
21st Mar 2022, 6:31 PM
NonStop CODING
NonStop CODING - avatar
+ 1
yeah output will be 5 because Talha has 5 characters output will be 5,4,4 your code is fine, i guess but there is no need to declare variable m, you can directly make i= 0 at the end
21st Mar 2022, 5:54 PM
NonStop CODING
NonStop CODING - avatar
0
I didn't get it?.What do you mean by i=0; at the end..I think there should be j=0;...My code is not working in Visual Studio code but it's working on online compiler...On vs code ,it's showing 5,5,5 and on online it's showing correct output.😂
21st Mar 2022, 6:11 PM
Muhammad Talha Atif
Muhammad Talha Atif - avatar
0
Hey, dude you said i=0 in upper comment..I know I got it .I just assigned new variable to make code look easier who don't know about that..Thank you for your feedback ..I was trying this code to work for 30 minutes .After your comments ,I run it on online compiler and it worked..Thanks for your suggestion 🥇
21st Mar 2022, 6:34 PM
Muhammad Talha Atif
Muhammad Talha Atif - avatar
0
yeah Great!🔥👍
21st Mar 2022, 6:35 PM
NonStop CODING
NonStop CODING - avatar