I am having trouble getting this program to work can someone show me what I am doing wrong?
Design, code, and test a function that accepts a pointer to a C-string as an argument – the function computes and returns the number of characters in the string. In the driver program prompt the user to input a string, pass the string to the function, and then display the function return value with an appropriate message.
// strLen() accepts a pointer to a C-string and returns the number of
// characters in the string
int strLen(char * s);
const int SIZE = 81; // size of char array
/* Sample output:
Enter a phrase of up to 80 characters:
sooner or later one of us must know if you just did what you're supposed to do
#include <iostream>
#include <cctype>
usingnamespace std;
// strLen() accepts a pointer to a C-string and returns the number of
// characters in the string
int strLen(char *s);
constint SIZE = 81; // size of char array
int main()
{
char *string;
int count;
cout << "Enter a phrase up to 80 characters: " << endl;
cin >> *string;
count = strLen(string);
cout << "The number of characters in this string is: " << count;
return 0;
}
int strLen(char *s)
{
int count = 0;
int k = 0;
while(s[k] != '\0')
{
count++;
k++;
}
return count;
Arrays and pointers are very similar but not the same.
Arrays have a size because the memory for them is automatically allocated.
Pointers are assigned either to an existing variable or to dynamically allocated memory.
You defined a pointer but did neither of the two above, so 'string' is uninitialized and points to an invalid memory address for which you don't have read/write permission. Any operation involving data in that address will cause the program to crash
To fix you can either define an array (which is what I suppose your assignment wants) or dynamically allocate memory for that pointer with new.
Another problem is that the extraction operator >> stops reading at the first whitespace, so it will only read up to "sooner". Like pogrady suggested cin.get() is a good solution but it will not automatically put a '\0' at the end of the string. I think cin.getline() does that though I didn't read well
Note cin >> *string;
Since 'string' is a pointer to char, '*string' is a char. Doing that makes the program call the extraction operator for chars, which reads a single character from the stream