Here is the problem as it is written in the book:

Write a function that accepts a C- string as an argument and returns the length of the C- string as a result. The function should count the number of characters in the string and return that number. Demonstrate the function in a simple program that asks the user to input a string, passes it to the function, and then displays the function’s return value.

I have written a program that does what is specified, except for the part where the USER inputs a string. I can get the program to work when I have a pre-defined string written in the code, but how would I change my code so that it accepts a user input and calculates the number of characters there? I have tried using cin, but I think I am doing it wrong...

Here is my code so far:

#include <iostream>
using namespace std;

// Create function prototypes.

int Count_characters(char str[]);

// Create main function.

int main()

{

char string[]="Starting out with C++";      // THIS IS WHAT I WANT TO CHANGE TO ACCEPT A USER INPUT.
int count;                                  // Holds number of characters

// Call the function.

count=Count_characters(string);

// Display the returned value.

cout<< "The number of characters in the string is: ";
cout<< count;

cin.ignore();
cin.get();

}

int Count_characters(char str[])
{

// Declare variables.

int count=0;        // Count variable
int i=0;            // Loop variable

// Loop to count characters

while(str[i]!='\0')
{
count++;
i++;
}

// Returning count.

return count;

}
#include <string>
...
...
string user_input;
cin >> user_input;

and since you are compelled to use a c-string for your function,

char* c_string = user_input.c_str();

or, using c-string directly

char string[255] = {0};

cin.getline(string,sizeof(string));

The difference between cin >> and cin.getline() is that cin >> stops reading the keyboard when it encounters the first white-space character, while cin.getline() only stops when either the buffer is fulled or the Enter key is detected. So if you want to put spaces in the string you have to use cin.getline().

Also, if you're not explicitly required to write a string length function, you can use strlen().

And if you're into optimising your function, you could do something like the following, but if you're only just starting C++, then don't listen to the next bit :)

unsigned int Count_characters(const char *string)
{
    unsigned int count = 0;
    while(string[count++]);
    return (count-1);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.