Char arrays and word counting - c++

I have spent the last two hours trying different methods to prevent the APPCRASH error I keep getting when I run this program, but I am having NO luck whatsoever. Basically, all this is is a simple word counting program for an assignment. It works fine up until it is to display the word count that the program found when it ran. At this point, it just freezes for a second or two, then pops up with an APPCRASH error, and closes. I don't know WHY this is happening, anyone care to let me know where I am going wrong?
int main()
{
//word counting programs
char *userInput = new char;
input(userInput);
displayResults(wordCount(userInput), userInput);
return 0;
}
/***************************************
Definition of function - input *
prompts the user to input a sentence *
and stores the sentence into a char *
array. *
Parameter: char [] *
****************************************/
void input(char userInput[])
{
cout << "Enter a sentence (no more than 100 characters) and I will count the words:" << endl;
cin.getline(userInput, 101);
}
/***************************************
Definition of function - wordCount *
Accepts the input char array and counts*
the words in the sentence. Returns an *
int value with the word count. *
Parameter: char [] *
Returns: an int with the word count *
****************************************/
int wordCount(char* userInput)
{
int count = 0;
int words = 1;
if(userInput[0] == '\0')
{
words = 0;
}
else if(userInput[0] == ' ' || userInput[0] == '\t')
{
cout << "Error: can not use a whitespace as the first character!" << endl;
words = -1;
}
else
{
while(userInput[count] != '\0')
{
if(userInput[count] == ' ')
{
words++;
}
count++;
}
}
return words;
}
/***************************************
Definition of function - displayResults*
Displays the word count for the user *
entered input. *
****************************************/
void displayResults(int wordCountResult, char userInput[])
{
if(wordCountResult == -1)
cout << "Error reading input!" << endl;
else if(wordCountResult == 0)
cout << "Nothing was entered." << endl;
else
{
cout << "You entered: " << userInput << endl;
cout << "That contains " << wordCountResult << " word(s)!" << endl;
}
}

You're allocating 1 byte and expect to fit 100 bytes there:
char *userInput = new char;
You should write instead:
char *userInput = new char[101];
Better yet, avoid using raw pointers, C-strings and new. Use std::string in C++.

You allocated only one character instead of an array
char *userInput = new char;
try to change the line above at least to
char *userInput = new char[101];

The statement char *userInput = new char just creates a pointer to a char, not a string.
You have to use a character array here, if you don't prefer std::string.
change char *userInput = new char to char userInput[101].
Also, you have to declare your functions before main(), so that they can be called from main().

using namespace std;
void input(char userInput[]);
int wordCount(char* userInput);
void displayResults(int wordCountResult, char userInput[]);
int main()
{
//word counting programs
char *userInput = new char;
input(userInput);
displayResults(wordCount(userInput), userInput);
return 0;
}
/***************************************
Definition of function - input *
prompts the user to input a sentence *
and stores the sentence into a char *
array. *
Parameter: char [] *
****************************************/
void input(char userInput[])
{
cout << "Enter a sentence (no more than 100 characters) and I will count the words:" << endl;
cin.getline(userInput, 101);
}
/***************************************
Definition of function - wordCount *
Accepts the input char array and counts*
the words in the sentence. Returns an *
int value with the word count. *
Parameter: char [] *
Returns: an int with the word count *
****************************************/
int wordCount(char* userInput)
{
int count = 0;
int words = 1;
if(userInput[0] == '\0')
{
words = 0;
}
else if(userInput[0] == ' ' || userInput[0] == '\t')
{
cout << "Error: can not use a whitespace as the first character!" << endl;
words = -1;
}
else
{
while(userInput[count] != '\0')
{
if(userInput[count] == ' ')
{
words++;
}
count++;
}
}
return words;
}
/***************************************
Definition of function - displayResults*
Displays the word count for the user *
entered input. *
****************************************/
void displayResults(int wordCountResult, char userInput[])
{
if(wordCountResult == -1)
cout << "Error reading input!" << endl;
else if(wordCountResult == 0)
cout << "Nothing was entered." << endl;
else
{
cout << "You entered: " << userInput << endl;
cout << "That contains " << wordCountResult << " word(s)!" << endl;
}
}

Related

Pig latin conversion using Cstrings

The program takes in a word given by the user and translates that to pig latin. I've gotten everything to work almost perfectly, but have run into two bugs. The first of which is when translating words that begin with consonants say "count", the output is "ounttcay" instead of "ountcay". The second bug is that when for three letter words like "egg" or "not" the output is "egg_\377ay" or "ottn\377ay". Is there a simple way to remove that duplicate character and get rid of those numbers?
Note - Unfortunately it has to be done using a Cstring
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int convertToPigLatin(char arr[50]);
bool isVowel(char ch);
int main() {
char userInput[50];
char answer = ' ';
do {
cout << "Enter a word to convert it to pig latin" << endl;
cin.getline(userInput, 50); //get user input
cout << "Your entered word is " << userInput << endl;
convertToPigLatin(userInput); //translate user's input into piglatin
cout << "Would you like to convert another word?" << endl;
cin >> answer;
cin.ignore(); //clear past user input
cin.clear();
} while (answer == 'Y' || answer == 'y');
return 0;
}
bool isVowel (char ch) {
switch (tolower(ch)) { //if the first character of the given input is a vowel
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
default:
return false;
}
}
int convertToPigLatin(char arr[50]) {
char newArr[50];
// string conjunctions[6] = {"and","but","for","nor","yet","the"}; //list of conjunctions not to be converted
size_t arrLength = strlen(arr); //holds length of input
for (int i = 0; i < arrLength; i++) { //make sure all characters in input are lower case for easier processing
newArr[i] = tolower(arr[i]);
}
char lastChar = newArr[0]; //save the first character in case it needs to be appended
if (atoi(arr) || arr[0] == '\0') { //if the input contains a number or begins with a null character print an error
cout << "Cannot translate inputs that contain numbers" << endl;
return -1;
} else if (arrLength <= 2) { // if the input is 2 or less characters
cout << newArr << endl; //print the input as is
cout << "Boring! Try somthing more than 2 characters long" << endl;
return 0;
} else if ((strstr(newArr, "and") && arrLength == 3) || (arrLength == 3 && strstr(newArr, "but")) || (arrLength == 3 && strstr(newArr, "for")) || (arrLength == 3 && strstr(newArr, "nor")) || (arrLength == 3 && strstr(newArr, "yet")) || (arrLength == 3 && strstr(newArr, "the"))) { //if the input is more than 2 characters long
cout << newArr << endl; //print the input as is
cout << "No conjucntions try again!" << endl;
return 0;
} else { //if the given input is three characters and is not a conjunction, being translation
if (isVowel(arr[0])) { //check if input's first character is a vowel
cout << "Your word in piglatin is "<< strcat(newArr, "ay") << endl; //print that string with 'ay' at the end (i.e. egg'ay')
return 0;
} else { //else if the given input starts with a consonant
for (int r = 1; r < arrLength; r++) {
newArr[r-1] = newArr[r];
newArr[arrLength] = lastChar;
}
cout << "Your word in piglatin is " << strcat(newArr, "ay") << endl;
return 0;
}
}
return 0;
}
You're not terminating newArr, and the last index of the input string is arrLength - 1.
int convertToPigLatin(char arr[50]) {
// Make sure newArr is properly terminated.
char newArr[50] = {0};
// [...]
} else { //else if the given input starts with a consonant
for (int r = 1; r < arrLength; r++) {
newArr[r-1] = newArr[r];
}
// Do this outside the loop.
newArr[arrLength-1] = lastChar;
// No need for strcat here.
cout << "Your word in piglatin is " << newArr << "ay" << endl;
}
}
return 0;
}
You need to add the '\0' at the end of newArr because strlen does not count it so you are not copying it. strcat replaces '\0' witn 'ay\0' but you have no '\0'.
for (int r = 1; r < arrLength; r++) {
newArr[r-1] = newArr[r];
newArr[arrLength] = lastChar;
}
newArr[arrLength+1] = '\0';
cout << "Your word in piglatin is " << strcat(newArr, "ay") << endl;

My c++ program doesn't complete and closes

This program counts the number of times a specific character appears in a string. The compiler shows me an incomplete output without displaying how many times the character shows in the input then closes abruptly
Enter a string (up to 50 characters): k;kl;kl;k;kljhh
Enter a character and I will tell you how many
times it appears in the string: k
k appears Press any key to continue...
I'm using VS community.
// This program demonstrates a function, countChars, that counts
// the number of times a specific character appears in a string.
#include <iostream>
using namespace std;
int countChars(char *, char); // Function prototype
int main()
{
const int SIZE = 51; // Array size
char userString[SIZE]; // To hold a string
char letter; // The character to count
// Get a string from the user.
cout << "Enter a string (up to 50 characters): ";
cin.getline(userString, SIZE);
// Get a character to count occurrences of within the string.
cout << "Enter a character and I will tell you how many\n";
cout << "times it appears in the string: ";
cin >> letter;
// Display the number of times the character appears.
cout << letter << " appears ";
cout << countChars(userString, letter) << " times.\n";
return 0;
}
//****************************************************************
// Definition of countChars. The parameter strPtr is a pointer *
// that points to a string. The parameter Ch is a character that *
// the function searches for in the string. The function returns *
// the number of times the character appears in the string. *
//****************************************************************
int countChars(char *strPtr, char ch)
{
int times = 0; // Number of times ch appears in the string
// Step through the string counting occurrences of ch.
while (*strPtr != '\0')
{
if (*strPtr == ch) // If the current character equals ch...
times++; // ... increment the counter
strPtr++; // Go to the next char in the string.
}
return times;
}
Unable to reproduce on Ubuntu. Perhaps a windows issue?
#include <iostream>
#include <iomanip>
class T590_t
{
std::stringstream ssin;
public:
T590_t() = default;
~T590_t() = default;
int exec(int , char** )
{
ssin << "k;kl;kl;k;kljhh\nk"; // for consistent behavior, use stringstream for input
// the letter ------------^
const int SIZE = 51; // Array size
char userString[SIZE]; // To hold a string
// Get a string from the user.
std::cout << "\n Enter a string (up to 50 characters): ";
(void)ssin.getline(userString, SIZE);
std::cout << "\n '" << userString << "'" << std::endl; // echo input
// Get a character to count occurrences of within the string.
std::cout << "\n Enter a character and I will tell you how many times it appears in the string: ";
char letter = '\0'; // The character to count, initialized
ssin >> letter;
std::cout << " '" << letter << "'" << std::endl; // echo input
// Display the number of times the character appears.
std::cout << "\n " << letter << " appears "
<< countChars(userString, letter) << " times.\n";
return 0;
}
private: // methods
int countChars(char *strPtr, char ch)
{
int times = 0; // Number of times ch appears in the string
// Step through the string counting occurrences of ch.
while (*strPtr != '\0')
{
if (*strPtr == ch) // If the current character equals ch...
times++; // ... increment the counter
strPtr++; // Go to the next char in the string.
}
return times;
}
}; // class T590_t
int main(int argc, char* argv[])
{
T590_t t590;
return t590.exec(argc, argv);
}
with output:
Enter a string (up to 50 characters):
'k;kl;kl;k;kljhh'
Enter a character and I will tell you how many times it appears in the string: 'k'
k appears 5 times.
You can pass an array of characters and its size instead:
int GetCharCount(char[], const int, const char);
int main(){
char text[] = "Hello there!";
cout << GetCharCount(text, strlen(text), 'e') << endl;
cout << endl << endl;
cin.get();
return 0;
}
int GetCharCount(char pTxt[], const int size, const char c){
int count = 0;
for(int i(0); i != size; i++)
if(c == pTxt[i])
count++;
return count;
}

Traversing an Inputted String and Returning a Specific Amount of Letters Within the String

I am working on a program that has the user input a letter then a string. Once the string is inputted the program should traverse the string and return the amount of the specific letter within the string. Here is the code I have so far:
#include <iostream>
using namespace std;
void countLetters(char letter[]);
/**********************************************************************
* Prompts the user for a line of input (using getline),
* calls countLetters(), and displays the number of letters.
***********************************************************************/
int main()
{
char letter[256];
countLetters(letter);
return 0;
}
/**********************************************************************
* Function to return the number of letters in a string.
***********************************************************************/
void countLetters(char Letter[])
{
char text[] = " ";
int count = 0;
cout << "Enter a letter: ";
cin >> letter;
cout << "Enter text: ";
cin >> text;
cin.getline(text, 256);
for (int i = (sizeof(text) / sizeof(text[0]) - 2); i >=0; i--)
{
if(text[i])
{
count++;
}
cout << "Number of '" << letter << "'s: " << count << endl;
}
}
/*
The output should be:
Enter a number: e
Enter a string: Hello, programming is fun
Number of 'e's: 1
*/
I have tried researching this and have found no help through this method of counting the amount of letters within the string the user inputs. Any help is appreciated, thank you.
Most issues have been pointed out in the comments. Here's a fixed version:
#include <iostream>
using namespace std;
void countLetters();
/**********************************************************************
* Prompts the user for a line of input (using getline),
* calls countLetters(), and displays the number of letters.
***********************************************************************/
int main()
{
// You create an array in the function, don't need one here, too
// char letter[256];
countLetters();
return 0;
}
/**********************************************************************
* Function to return the number of letters in a string.
***********************************************************************/
void countLetters()
{
// Your method creates an array of only 2 bytes
//char text[] = " ";
char text[256];
int count = 0;
// You forgot to declare letter
char letter;
cout << "Enter a letter: ";
cin >> letter;
// Reading the char leaves a new line. Consume. cin.ignore is another way
cin.getline(text, 256);
cout << "Enter text: ";
cin.getline(text, 256);
// Overly complicated
//for (int i = (sizeof(text) / sizeof(text[0]) - 2); i >=0; i--)
for (int i = 0; text[i]; i++)
{
// Compare to letter
if (text[i] == letter)
{
count++;
}
// This needs to be outside the loop
//cout << "Number of '" << letter << "'s: " << count << endl;
}
cout << "Number of '" << letter << "'s: " << count << endl;
}
In C++, it's almost always better to use std::string instead of raw char arrays, but I'll assume this is an assignment and arrays are required.

Declaring a function from another source file "no matching function to call"

I'm writing a source and header file that are implemented by a program with some other files, and I need to make the code work by only editing the one source/header files (game.h and game.cpp). I'm trying to call another function from another source/header file, but it's not working right. Here's my code
game.cpp
#include "game.h"
#include "guesser.h"
#include "provider.h"
using namespace std;
const char FILL_CHARACTER = '.';
string wordSoFar;
int numMissedGuesses;
const int MAX_MISTAKE_LIMIT = 10;
void Game::setUpGame (int wordLength)
{
wordSoFar = string(wordLength, FILL_CHARACTER);
numMissedGuesses = 0;
}
bool Game::guesserHasWon()
{
return wordSoFar.find(FILL_CHARACTER) == string::npos;
}
bool Game::guesserHasLost()
{
return numMissedGuesses >= MAX_MISTAKE_LIMIT;
}
void Game::guessHasBeenMade (char guess)
{
bool isInWord;
Provider::getResponseToGuess(guess, isInWord, wordSoFar);
if (isInWord)
{
characterIsInWord (guess, wordSoFar);
}
else
{
++numMissedGuesses;
characterIsNotInWord (guess);
}
}
game.h
#ifndef GAME_H
#define GAME_H
#include <string>
class Provider;
class Guesser;
class Game{
const char FILL_CHARACTER;
std::string wordSoFar;
int numMissedGuesses;
const int MAX_MISTAKE_LIMIT;
void setUpGame (int wordLength);
bool guesserHasWon();
bool guesserHasLost();
void guessHasBeenMade (char guess);
};
#endif
provider.h
#ifndef PROVIDER_H
#define PROVIDER_H
#include <string>
class Provider {
public:
int initialPrompt ();
void getResponseToGuess (char guess, bool& isInWord,
std::string& wordSoFar,
int numMissedGuesses);
std::string providerHasWon ();
void providerHasLost (std::string wordSoFar);
private:
};
#endif
provider.cpp
#include "provider.h"
#include "game.h"
#include <iostream>
using namespace std;
int Provider::initialPrompt ()
{
cout << "Let's play Hangman!\n\n"
<< "Please think of a word from 4-9 characters long. The word\n"
<< "should not be a proper name (something that you would normally\n"
<< "capitalize, nor should it contain any punctuation characters.\n"
<< "\n\nOK, got a word?\n" << endl;
int len = 1;
while (len < 4 || len > 9)
{
cout << "How long is your word? " << flush;
cin >> len;
if (len < 4 || len > 9)
{
cout << "Please choose a word between 4 and 9 characters long."
<< endl;
}
}
return len;
}
bool getYesNoResponse()
{
string response;
getline (cin, response);
while (response.size() == 0 ||
(response[0] != 'y' && response[0] != 'Y'
&& response[0] != 'n' && response[0] != 'N'))
{
if (response.size() > 0)
cout << "Please respond 'yes' or 'no'. " << flush;
getline (cin, response);
}
return response[0] == 'y' || response[0] == 'Y';
}
void Provider::getResponseToGuess (char guess, bool& isInWord,
std::string& wordSoFar,
int numMissedGuesses)
{
cout << "I have missed " << numMissedGuesses << " guesses ("
<< Game::MAX_MISTAKE_LIMIT - numMissedGuesses << " misses left)"
<< endl;
cout << "\n" << wordSoFar << "\n";
for (int i = 1; i <= wordSoFar.size(); ++i)
cout << i;
cout << "\n\nDoes your word contain the letter '"
<< guess << "'? (y/n) " << flush;
isInWord = getYesNoResponse();
if (isInWord) {
string response;
bool done = false;
string newWord;
while (!done)
{
cout << "Enter all of the character positions (1-"
<< wordSoFar.size() << ") in which the letter '"
<< guess << "' appears: " << flush;
getline (cin, response);
bool digitsFound = false;
newWord = wordSoFar;
for (int i = 0; i < response.size(); ++i)
{
char d = response[i];
if (d >= '1' && d <= '0' + wordSoFar.size())
{
int k = d - '1';
if (wordSoFar[k] == Game::FILL_CHARACTER)
{
newWord[k] = guess;
digitsFound = true;
}
}
}
if (digitsFound)
{
cout << "Like this: " << newWord << "? (y/n) " << flush;
bool yn = getYesNoResponse();
if (yn)
{
wordSoFar = newWord;
done = true;
}
}
}
}
}
/**
* Announce that the provider has won the game, and get the
* provider's actual word.
*/
std::string Provider::providerHasWon ()
{
cout << "Congratulations, you have won." << endl;
cout << "\nOut of curiosity, what was your word? " << flush;
string answer;
getline (cin, answer);
return answer;
}
/**
* Announce that the guesser has won the game, and get the
* provider's actual word.
*/
void Provider::providerHasLost (string wordSoFar)
{
cout << wordSoFar
<< "\n\nI have won!\nThanks for playing" << endl;
}
My problem is the line
Provider::getResponseToGuess(guess, isInWord, wordSoFar);
It was originally just
getResponseToGuess(guess, isInWord, wordSoFar);
but I've tried several variations. I've tried Provider::Provider and Provider.getReponseToGuess, and a bunch of others, but nothing seems to work. Can anyone help me with this? I'm just trying to call the function from the provider files.
EDIT: I have the same problem calling a function from the guesser files, I tried doing it the same way I did with provider, but it gives me the error "no matching function for call to Guesser::Guesser();
Provider providerobj;
Guesser guesserobj;
providerobj.getResponseToGuess(guess, isInWord, wordSoFar, numMissedGuesses);
if (isInWord)
{
guesserobj.characterIsInWord(guess, wordSoFar);
}
I tried doing it the same way as I did with providerobj, but it won't work for some reason.
Here's the code for guesser.
guesser.cpp
#include "guesser.h"
#include "game.h"
#include <iostream>
#include <fstream>
using namespace std;
const std::string Guesser::alphabet = "abcdefghijklmnopqrstuvwxyz";
// Initialize the guesser for a game wit hthe indicated wordlength,
// using words from an indicated file.
Guesser::Guesser (int wordLength, const char* wordListFilename)
{
for (int i = 0; i < 26; ++i)
charactersTried[i] = false;
string word;
ifstream in (wordListFilename);
while (in >> word)
{
if (word.size() == wordLength)
{
// word is of desired length
if (word.find_first_not_of(alphabet) == string::npos) {
// word contains only lowercse alphabetics
possibleSolutions.push_back (word);
}
}
}
in.close();
}
/**
* Scan the words that are possible solutions so far, counting, for
* each letter not already tried, the number of words with that letter.
* Guess the letter that occurs in the most words.
*/
char Guesser::guessACharacter()
{
int counts[26];
for (int i = 0; i < 26; ++i)
counts[i] = 0;
// Count the number of words in which each letter can be found
for (int i = 0; i < possibleSolutions.size(); ++i)
{
string word = possibleSolutions[i];
for (char c = 'a'; c <= 'z'; ++c)
{
if (!charactersTried[c- 'a'])
{
// Character c has not been tried yet
if (word.find(c) != string::npos)
// c is in this word
++counts[c - 'a'];
}
}
}
// Find the character that occurs in the most words
char guess = ' ';
int maxSoFar = -1;
for (char c = 'a'; c <= 'z'; ++c)
{
if (counts[c - 'a'] > maxSoFar)
{
guess = c;
maxSoFar = counts[c - 'a'];
}
}
if (maxSoFar <= 0)
{
guess = 'a';
while (charactersTried[guess-'a'])
++guess;
}
charactersTried[guess-'a'] = true;
return guess;
}
/**
* Following a successful guess of a letter in the word, make a pass through
* the possibleSolutions, removing all words that do not contain the
* guess character in the positions indicated in wordSoFar.
*/
void Guesser::characterIsInWord (char guess, const string& wordSoFar)
{
vector<string> remainingSolutions;
for (int i = 0; i < possibleSolutions.size(); ++i)
{
string wd = possibleSolutions[i];
bool OK = true;
for (int k = 0; OK && k < wordSoFar.size(); ++k)
{
if (wordSoFar[k] == guess)
{
if (wd[k] != guess)
{
OK = false;
}
}
}
if (OK)
{
//cerr << "Keeping " << wd << endl;
remainingSolutions.push_back (wd);
}
}
possibleSolutions = remainingSolutions;
}
/**
* Following a mistaken guess of a letter in the word, make a pass through
* the possibleSolutions, removing all words that contain the
* guess character.
*/
void Guesser::characterIsNotInWord (char guess)
{
vector<string> remainingSolutions;
for (int i = 0; i < possibleSolutions.size(); ++i)
{
string wd = possibleSolutions[i];
if (wd.find(guess) == string::npos)
{
remainingSolutions.push_back (wd);
}
}
possibleSolutions = remainingSolutions;
}
/**
* Guesser has lost the game. Look at the provider's actual word
* and gripe a bit about losing.
*/
void Guesser::admitToLoss (std::string actualWord, const string& wordSoFar)
{
bool match = actualWord.size() == wordSoFar.size();
for (int i = 0; match && i < actualWord.size(); ++i)
{
match = wordSoFar[i] == Game::FILL_CHARACTER ||
wordSoFar[i] == actualWord[i];
}
if (!match)
{
cout << "Ummm...your word '" << actualWord
<< "' does not match the patterh '"
<< wordSoFar <<"'.\nDid you make a mistake somewhere?"
<< endl;
}
else
{
for (int i = 0; match && i < actualWord.size(); ++i)
{
if (wordSoFar[i] == Game::FILL_CHARACTER
&& charactersTried[actualWord[i]-'a'])
{
cout << "Did you forget to mention the '"
<< actualWord[i]
<< "' in position " << i+1 << "?"
<< endl;
return;
}
}
for (int i = 0; (!match) && i < possibleSolutions.size(); ++i)
match = (actualWord == possibleSolutions[i]);
match = match && (possibleSolutions.size() > 0);
if (match)
{
cout << "OK, I might have guessed that eventually." << endl;
}
else
{
cout << "Interesting, I don't know that word. Are you sure you\n"
<< "spelled it correctly?." << endl;
}
}
}
guesser.h
#ifndef GUESSER_H
#define GUESSER_H
#include <string>
#include <vector>
class Game;
class Guesser {
public:
// Initialize the guesser for a game with the indicated wordlength,
// using words from an indicated file.
Guesser (int wordLength, const char* wordListFilename);
/**
* Scan the words that are possible solutions so far, counting, for
* each letter not already tried, the number of words with that letter.
* Guess the letter that occurs in the most words.
*/
char guessACharacter();
/**
* Following a successful guess of a letter in the word, make a pass through
* the possibleSolutions, removing all words that do not contain the
* guess character in the positions indicated in wordSoFar.
*/
void characterIsInWord (char guess, const std::string& wordSoFar);
/**
* Following a mistaken guess of a letter in the word, make a pass through
* the possibleSolutions, removing all words that contain the
* guess character.
*/
void characterIsNotInWord (char guess);
/**
* Guesser has lost the game. Look at the provider's actual word
* and gripe a bit about losing.
*/
void admitToLoss (std::string actualWord, const std::string& wordSoFar);
private:
// A collection of words that match all guesses made so far
std::vector<std::string> possibleSolutions;
// Tracks characters already guessed.
// charactersTried[c-'a'] is true if the character c
// has been guessed previously
bool charactersTried[26];
static const std::string alphabet;
};
#endif
Provider::getResponseToGuess(guess, isInWord, wordSoFar); will not work because, getResponseToGuess is not a static function.
Provider.getReponseToGuess also wrong because Provider is a class, not an object, you can't call a member function of a class with class name.
you have to create a object of the class first, then call the member function with the object.
Provider provider_obj;
proveder_obj.getResponseToGuess(guess, isInWord, wordSoFar);
if you are new to C++, I would suggest first try some basic programs.

C++: Will Not Accept New C-String Input

First off, thanks in advance for your help. This issue is driving me nuts.
I have a program that accepts a c-string, and then can count the number of vowels and consonants. This works without issue. However, I also need to include a function that allows the user to create a new string. The problem is, though, when the user selects "new string" from the menu, it just loops through the newString() method, without waiting for the user's input. It then creates a new, blank screen.
Here is the entire program. The newString() method is at the end.
#include <iostream>
using namespace std;
// function prototype
void printmenu(void);
int vowelCount(char *);
int consCount(char *);
int cons_and_vowelCount(char *);
void newString(char *, const int);
int main() {
const int LENGTH = 101;
char input_string[LENGTH]; //user defined string
char choice; //user menu choice
bool not_done = true; //loop control flag
// create the input_string object
cout << "Enter a string of no more than " << LENGTH-1 << " characters:\n";
cin.getline(input_string, LENGTH);
do {
printmenu();
cin >> choice;
switch(choice)
{
case 'a':
case 'A':
vowelCount(input_string);
break;
case 'b':
case 'B':
consCount(input_string);
break;
case 'c':
case 'C':
cons_and_vowelCount(input_string);
break;
case 'd':
case 'D':
newString(input_string, LENGTH);
break;
case 'e':
case 'E':
exit(0);
default:
cout << endl << "Error: '" << choice << "' is an invalid selection" << endl;
break;
} //close switch
} //close do
while (not_done);
return 0;
} // close main
/* Function printmenu()
* Input:
* none
* Process:
* Prints the menu of query choices
* Output:
* Prints the menu of query choices
*/
void printmenu(void)
{
cout << endl << endl;
cout << "A) Count the number of vowels in the string" << endl;
cout << "B) Count the number of consonants in the string" << endl;
cout << "C) Count both the vowels and consonants in the string" << endl;
cout << "D) Enter another string" << endl;
cout << "E) Exit the program" << endl;
cout << endl << "Enter your selection: ";
return;
}
int vowelCount(char *str) {
char vowels[11] = "aeiouAEIOU";
int vowel_count = 0;
for (int i = 0; i < strlen(str); i++) {
for (int j = 0; j < strlen(vowels); j++) {
if (str[i] == vowels[j]) {
vowel_count++;
}
}
}
cout << "String contains " << vowel_count << " vowels" << endl;
return vowel_count;
} // close vowelCount
int consCount(char *str) {
char cons[43] = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
int cons_count = 0;
for (int i = 0; i < strlen(str); i ++) {
for (int j = 0; j < strlen(cons); j++) {
if (str[i] == cons[j]) {
cons_count++;
}
}
}
cout << "String contains " << cons_count << " consonants" << endl;
return cons_count;
} // close consCount
int cons_and_vowelCount(char *str) {
int cons = consCount(str);
int vowels = vowelCount(str);
int total = cons + vowels;
cout << "The string contains a total of " << total << " vowels and "
"consonants" << endl;
return total;
}
void newString(char *str, int len) {
cout << "Enter a string of no more than " << len-1 << " characters:\n";
cin.getline(str, len);
return;
}
The statement cin >> choice only consumes the character they type, not the carriage return that follows. Thus, the subsequent getline() call reads an empty line. One simple solution is to call getline() instead of cin >> choice and then use the first character as the choice.
BTW, the while (not done) should immediately follow the do { … }, and the return 0 is redundant. Also, you should call newString at the start of the program instead of repeating its contents.
cin >> choice leaves a newline in the input stream.. which cause the next getline() to consume it and return. There are many ways.. one way is to use cin.ignore() right after cin >> choice.
The cin >> choice only consumes one character from the stream (as already mentioned). You should add
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
right after cin>>choice to ignore all the characters that come into the stream after reading the choice.
p.s. #include <limits>