Volunteer C++ Gurus. Thank you in advance for your time. This site has saved my sanity.
I am working with my longWords function and cannot get it to stop displaying the same value (2293264).
I know that my code is a little janky because I modified it from array format to a pointer function. How do you convert and have the same functionality? Here is my work.
#include <iostream>
#include <string>
using namespace std;
// Function prototypes
int countWords(char *);
int longWords(char *);
void sentSlice(char []);
int main()
{
const int SIZE = 257; // Array size
char line[SIZE]; // To hold the user's sentence
char *str1;
char *str2;
// Get string from user
cout << "Enter a string (up to 256 characters): ";
cin.getline(line, SIZE);
// Store string in pointer array
str1 = line;
str2 = line;
// Display original sentence
sentSlice(str1);
cout << "\n";
cout << "Original Order:\n";
cout << str1 << "\n\n";
// Display letters backwards
cout << "Backwards:\n";
for (int j = strlen(str1); j != 0; j--)
{
cout << str1[j];
}
cout << "\n\n";
system("PAUSE");
// Display the number of words in the sentence
cout << "\nNumber of words: ";
cout << countWords(str1) << "\n";
// Display the longest word length
cout << "Longest word length: ";
cout << longWords(str2);
cout << endl << "\n";
system("PAUSE");
return 0;
}
//******************************************************************
// Definition of function sentSlice. This function accepts a *
// character array as its argument. It scanes the array looking *
// for a space. When it finds one, it executes a vertical shift. *
// pg. 514 *
//******************************************************************
void sentSlice(char userSent[])
{
int count = 0; // Loop counter
// Locate the spaces and replace with new line operator
while (userSent[count] != '\0')
{
if (userSent[count] == ' ')
userSent[count] = '\n';
count++;
}
}
//*******************************************************************
// Definition of countWords. userSent is a pointer that points to a *
// string. The function returns the number of words in the string *
// pg. 516 *
//*******************************************************************
int countWords(char *userSent)
{
int times = 0; // Number of times a space appears in the string
// Step through the string counting occurences of a space
while(*userSent != '\0')
{
if (*userSent == '\n')
times++;
*userSent++;
}
return (times + 1);
}
//*******************************************************************
// Definition of longWords. userSent2 is a pointer that points to a *
// string. The function returns the length of the longest word in *
// the string. *
//*******************************************************************
int longWords(char *userSent2)
{
int times = 0;
int counter = 0;
int maxWord = -1;
if (*userSent2 != '\n')
{
counter++;
}
else if (*userSent2 == '\n')
{
if (counter > maxWord)
{
maxWord = counter;
}
counter = 0;
}
}