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; }
5 Respuestas
+ 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;
}
+ 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
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.😂
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 🥇
0
yeah Great!🔥👍