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;
}