-1

I am struggling with an assignment for my first c++ class. I am hoping someone can help me in the right direction. I need to write a "recursive version of strlen in c strings." According to my handout, my function should look like this, "int str_length(char s[])".

My main problem is trying to get the user to enter a string or cstring of an undetermined length and use it for the function call. I would really appreciate all the help and direction I can get.

I have played around with my code so much now that I am rather lost. It would seem I would fix one issue and create a new one. I think I have my function written correctly but here is the code if there is a better/correct way of doing it.

#include <iostream>
#include <cstring> //included both until I find my solution
#include <string>
using namespace std;


//string or char sentence;  This part of my struggle
char choice = 'Y';
int str_length(char s[]);


int main()
{

    while ((choice != 'n') && (choice != 'N'))
    {

        cout << "Enter a sentence. ";
        //user entry cin, getline etc
        cout << sentence;
        //cout << str_length(sentence);
        cout << endl;

        cout << "Do you want to have another run? Y/N ";
        cin >> choice; 
    }

}



int str_length(char s[])
{
    // if we reach at the end of the string 
    if (s == '\0')
    {
        return 0;
    }
    else
    {
        return 1 + str_length(s + 1);
    }
}
  • 6
    why are you still struggling when the code works as expected? What is the problem? – 463035818_is_not_a_number Nov 27 '19 at 14:59
  • 2
    Are you just asking how to use [std::getline()](https://en.cppreference.com/w/cpp/string/basic_string/getline)? – Frank Nov 27 '19 at 14:59
  • 3
    is the problem that you get the "wrong" length for eg "This is a sentence with several seperate words and cout will only read the first word, while you should use getline to read the full line" ? If yes you should mention that in the question – 463035818_is_not_a_number Nov 27 '19 at 15:00
  • You haven't declared what `sentence` is! Sorry - missed the `//` bit in your code. – Adrian Mole Nov 27 '19 at 15:01
  • 2
    `cin >> sentence;` won't work. Specifically it reads up until the first whitespace. The bug is not in the code that is shown. You probably want to use `std::getline()` as suggested in the comments above. – drescherjm Nov 27 '19 at 15:02
  • 2
    Why do you have as the title "recursive version of strlen", but your issue has absolutely nothing to do with this? The issue with misidentifying the problem is that persons will search for "recursive version of strlen", and come across this thread that has to do with reading input. – PaulMcKenzie Nov 27 '19 at 15:07
  • Related: [https://stackoverflow.com/questions/9469264/c-cin-only-reads-the-first-word](https://stackoverflow.com/questions/9469264/c-cin-only-reads-the-first-word) – drescherjm Nov 27 '19 at 15:09
  • Please forgive my newbie post. This is my first programming class and my first post for help. so if I use char sentence[500]; cin.getline(sentence, 500) // I get an Access violation writing location I am not sure what to use as my variable and my user input. – user12446497 Nov 27 '19 at 15:15
  • If you want to compare the first charactor of s with '\0' then you need to dereference s first. I think you want ```if (*s == '\0')``` – Wolfgang Brehm Nov 27 '19 at 15:17
  • try ```string line; getline(cin,line); cout << str_length(line.c_str()) << endl;``` – Wolfgang Brehm Nov 27 '19 at 15:20
  • if (*s == '\0') -- along with cin.getline(sentence, 500) -- seems to be operating properly. But on the second cycle after choice it is skipping the cin.getline and going straight to cin >> choice. I will see if I can figure out why that is happenin now. Thanks for your help! – user12446497 Nov 27 '19 at 15:30
  • Releated to the new problem: [https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – drescherjm Nov 27 '19 at 15:35
  • I had this fixed yesterday with cin.ignore(); Thank you for the link though, it saved me a bit of time remembering after I read it. – user12446497 Nov 27 '19 at 15:49

1 Answers1

2

There is already the standard C function strlen that has the following declaration

size_t strlen( const char *s );

So your recursive function should have the same declaration. It can be implemented the following way

size_t strlen( const char *s )
{
    return *s == '\0' ? 0 : 1 + strlen( s + 1 );
}

A program that tests the function can look like

#include <iostream>
#include <string>
#include <limits>

size_t strlen( const char *s )
{
    return *s == '\0' ? 0 : 1 + strlen( s + 1 );
}

int main()
{
    char choice;

    do
    {
        std::cout << "Enter a sentence: ";

        std::string sentence;

        std::getline( std::cin, sentence );

        std::cout << "The length of the sentence is "
                  << strlen( sentence.c_str() )
                  << '\n';

        std::cout << "Do you want to have another run (Y/N)? ";

        std::cin >> choice;
        std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
    } while ( choice == 'y' || choice == 'Y' );        
}

Its output might be

Enter a sentence: Hello user12446497
The length of the sentence is 18
Do you want to have another run (Y/N)? n
Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268
  • Although this works and I tried it out in my code. I'm not sure if I can use this method. It varies from the instructors comment of "the function will looks like this: int str_length(char s[])" I like your way better as it will not limit the length of the string. . – user12446497 Nov 27 '19 at 16:39
  • @user12446497 If you need then you may redeclare the function like int str_length( char s[] ); though this declaration is not good because it confuses readers. For example they can think that the function changes the ;passed string. – Vlad from Moscow Nov 27 '19 at 17:00