Answer to Question #161129 in C++ for zain ul abdeen

Question #161129

Write a function named len which takes as input a char array of size 255 and returns the length of the actual string in it. (Note: A string ends with ‘\0’ but it is not included in the length calculation.) In the main get a string from the user (fgets) and pass it to len as an argument. Main should then display the string’s length.


1
Expert's answer
2021-02-06T10:10:09-0500
#include <iostream>
#include <cstring>
using namespace std;


int len(char str[255])
{
    int count = 0;
    char c = str[0];
    while(c!='\0')
    {
        count++;
        c = str[count];
    }
    return count;//if you don't want to count \n symbol, comment this
    //return count - 1; //and uncomment this
}
int main()
{
    char str[255];
    fgets(str, 255, stdin);
    cout << "Our function: " << len(str) << endl;
    cout << "C++ function: " << strlen(str) << endl;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog