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.
#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;
}
Comments
Leave a comment