Counting Characters in C++ - c++

Not sure why my loop isn't working, it keeps sticking every time I try an input :/
Am hoping for an onput that just shows the count of the diffent types which I've listed.
#include <iostream>
#include <string>
#include <iomanip>
#include <cctype>
using namespace std;
int main() {
char ch;
int puncCount = 0;
int letterCount = 0;
int digitCount = 0;
int spaceCount = 0;
cout << "The characters which you'd like!" << endl;
cout << "Type a line with a single 'Q' to stop \n" << endl;
cin.get(ch);
while (ch != 'q')
{
letterCount += isalpha(ch);
puncCount += ispunct(ch);
digitCount += isalnum(ch);
spaceCount += isspace(ch);
}
cout << "Letter count is" << letterCount << endl;
cout << "Puncuation count is" << puncCount << endl;
cout << "Digit count is" << digitCount << endl;
cout << "Space count is" << spaceCount << endl;
return 0;
}

You need to put another call to get input within the loop:
while (ch != 'q')
{
// ...
cin.get(ch);
}

You are not repeating the call to get the characters in the loop. Also, check for 'q' and'Q' if that is your aim.

Related

Why does my try catch exception stop working after the catch?

I have a segment of code here that runs partially. I am able to input both the characters (c, a, r) and numbers initially, but after entering a character input, the code no long accepts integer inputs. Why does this happen?
I think it has something to do with my try catch exception.
code:
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
int item;
string input;
float total = 0;
int flag = 0;
float maintotal = 0;
int main() {
cout.precision(2);
cout << std::fixed;
cout << "Vending Machine" << endl;
cout << "----Items------" << endl;
vendingMachine();
cout << "Enter c to checkout" << endl;
cout << "Enter a to add items" << endl;
cout << "Enter r to remove items" << endl;
while (true) {
cout << "Enter your selection: " << flush;
cin >> input;
try
{
item = stoi(input); //convert to int
}
catch (exception &e)
{
//std::cout << e.what();
flag = -1; //if not set flag
if (input == "c"){
checkout();
}
if (input == "a") {
add();
cout << "mainadd total: " << total << endl;
}
if (input == "r") {
remove();
}
}
if (flag != -1) //only execute with no errors
{
total = enterSelection();
cout << "total from main: " << total << endl;
}
}
return 0;
}
Once you've set flag to -1, it's never changed back to 0. The initialization you perform at the top of the file happens just once, before main is even called. So, after that, when you set it to -1 in the catch block, it never went to a part of the code that set it back to 0. As you saw, setting flag = 0 at the beginning of the while loop corrects that omission.

Hangman only gets first letter of secret word

I am trying to write a hangman program for an assignment. I've written code I thought would work, yet when testing it with the secret word, "IMPOSSIBLE", it only reads the "I" and nothing else. I tried changing all my strings to character lists but I don't think that was the issue. Does anyone have any advice on what I am doing incorrectly?
Thanks,
Keith.
Here is the code:
/* CSCI 261 Assignment 5: Hang Man Game
*
* Author: Keith Danielson
*
* A program that runs a simple hang man game
*/
// The include section adds extra definitions from the C++ standard library.
#include <iostream> // For cin, cout, etc.
#include <string>
// We will (most of the time) use the standard library namespace in our programs.
using namespace std;
//Defining the secret word as a constant
//const string SECRET_WORD = "IMPOSSIBLE";
int main() {
const char SECRET_WORD[10] = {'I','M','P','O','S','S','I','B','L','E'};
const int SECRET_WORD_LENGTH = 10;
//Defining the number of wrong guesses available, found letters, wrong guesses, and user choice.
int guesses = 7;
char foundLetters[SECRET_WORD_LENGTH];
char wrongGuesses[guesses];
char userChoice;
//Filling foundLetters with underslashes based on the length of the secret word.
for (int i = 0; i <= SECRET_WORD_LENGTH; i++) {
foundLetters[i] = '_';
}
cout << "Welcome to hangman!" << endl;
for (int i = 0; i <= 7; i++) {
if (guesses == 0){
break;
}
cout << "Take a guess: ";
for (int j = 0; j <= SECRET_WORD_LENGTH; j++) {
cout << foundLetters[j] << " ";
}
cout << "\n" << "Your guess: ";
cin >> userChoice;
//if the user input is lowercase it'll be made upper case.
if (islower(userChoice)) {
userChoice = toupper(userChoice);
}
for (int j = 0; j <= SECRET_WORD_LENGTH; j++) {
//if (userChoice == foundLetters[j]) {
// cout << "You already guessed" << userChoice << "." << endl;
// break;
//}
if (userChoice == SECRET_WORD[j]) {
cout << "There's a " << userChoice << "!" << endl;
foundLetters[j] = userChoice;
break;
}
else if (userChoice != SECRET_WORD[j]) {
guesses = guesses - 1;
cout << "Sorry. No " << userChoice << "'s." << endl;
wrongGuesses[i] = userChoice;
if (guesses == 0) {
cout << "You lose! Try again.";
break;
}
else {
cout << "You have " << guesses << " remaining." << endl;
break;
}
}
}
}
return 0; // signals the operating system that our program ended OK.
}
Try something more like this instead:
// The include section adds extra definitions from the C++ standard library.
#include <iostream> // For cin, cout, etc.
#include <string>
#include <limits>
// We will (most of the time) use the standard library namespace in our programs.
using namespace std;
//Defining the secret word as a constant
const char SECRET_WORD[10] = {'I','M','P','O','S','S','I','B','L','E'};
const int SECRET_WORD_LENGTH = 10;
//Defining the number of wrong guesses available
const int WRONG_GUESSES = 7;
bool hasLetter(const char *letters, int numLetters, char ch) {
for (int i = 0; i < numLetters; ++i) {
if (letters[i] == ch) {
return true;
}
}
return false;
}
int main() {
char foundLetters[SECRET_WORD_LENGTH];
int foundLetters = 0;
char wrongLetters[WRONG_GUESSES];
int wrongLettersLength = 0;
int wrongGuessesLeft = WRONG_GUESSES;
char userChoice;
int found;
//Filling foundLetters with underslashes based on the length of the secret word.
for (int j = 0; j < SECRET_WORD_LENGTH; ++j) {
foundLetters[j] = '_';
}
cout << "Welcome to hangman!" << endl;
while (true) {
cout << "Take a guess: ";
for (int j = 0; j < SECRET_WORD_LENGTH; ++j) {
cout << foundLetters[j] << " ";
}
cout << "\n";
cout << "Your guess: ";
cin >> userChoice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//if the user input is lowercase it'll be made upper case.
userChoice = toupper(userChoice);
if (hasLetter(foundLetters, SECRET_WORD_LENGTH, userChoice) ||
hasLetter(wrongGuesses, wrongGuessesLength, userChoice))
{
cout << "You already guessed " << userChoice << "." << endl;
continue;
}
found = 0;
for (int j = 0; j < SECRET_WORD_LENGTH; ++j) {
if (SECRET_WORD[j] == userChoice) {
foundLetters[j] = userChoice;
++found;
}
}
if (found > 0) {
cout << "There's " << found << " " << userChoice << (found > 1 ? "'s" : "") << "!" << endl;
foundLettersLength += found;
if (foundLettersLength == SECRET_WORD_LENGTH) {
cout << "You win!";
break;
}
}
else {
cout << "Sorry. No " << userChoice << "'s." << endl;
wrongLetters[wrongLettersLength++] = userChoice;
if (--wrongGuessesLeft == 0) {
cout << "You lose! Try again.";
break;
}
cout << "You have " << wrongGuessesLeft << " guess" << (wrongGuessesLeft > 1 ? "es" : "") << " remaining." << endl;
}
}
return 0; // signals the operating system that our program ended OK.
}
Alternatively:
// The include section adds extra definitions from the C++ standard library.
#include <iostream> // For cin, cout, etc.
#include <string>
#include <limits>
#include <set>
// We will (most of the time) use the standard library namespace in our programs.
using namespace std;
//Defining the secret word as a constant
const string SECRET_WORD = "IMPOSSIBLE";
//Defining the number of wrong guesses available
const int WRONG_GUESSES = 7;
int main() {
//Filling foundLetters with underslashes based on the length of the secret word.
string foundLetters(SECRET_WORD.size(), '_');
set<char> guessedLetters;
int wrongGuessesLeft = WRONG_GUESSES;
char userChoice;
int found;
cout << "Welcome to hangman!" << endl;
while (true) {
cout << "Take a guess: ";
for (int j = 0; j < foundLetters.size(); ++j) {
cout << foundLetters[j] << " ";
}
cout << "\n";
cout << "Your guess: ";
cin >> userChoice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//if the user input is lowercase it'll be made upper case.
userChoice = toupper(userChoice);
if (!guessedLetters.insert(userChoice).second)
{
cout << "You already guessed " << userChoice << "." << endl;
continue;
}
string::size_type pos = SECRET_WORD.find(userChoice);
if (pos != string::npos) {
found = 0;
do {
foundLetters[pos] = userChoice;
++found;
pos = SECRET_WORD.find(userChoice, pos+1);
}
while (pos != string::npos);
cout << "There's " << found << " " << userChoice << (found > 1 ? "'s" : "") << "!" << endl;
if (foundLetters == SECRET_WORD) {
cout << "You win!";
break;
}
}
else {
cout << "Sorry. No " << userChoice << "'s." << endl;
if (--wrongGuessesLeft == 0) {
cout << "You lose! Try again.";
break;
}
cout << "You have " << wrongGuessesLeft << " guess" << (wrongGuessesLeft > 1 ? "es" : "") << " remaining." << endl;
}
}
return 0; // signals the operating system that our program ended OK.
}

How do I check if the input is letter?

I'm trying to display "invalid option" when the user enters a letter instead of a number. I tried using the isalpha() function but I get an infinite loop showing 0 Invalid option!try again:. The 0 from the output is displayed when entering a letter. When I actually type in the number 0 the message is displayed and the loop is exited.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std;
int main() {
// Vaules do not change
const int minNum = 1;
const int maxNum = 100;
int userInput;
// Changes every second
srand(time(0));
// Random number is stored
const int answer = minNum + (rand() % maxNum);
cout << answer << endl; // For testing purposes
cout << "Guess a number 1-100: ";
cin >> userInput;
cout << endl;
if(userInput == answer) {
cout << "Correct!\n\n";
}
while(userInput != answer) {
if(userInput < 1 || userInput > 100 || isalpha(userInput)) {
cout << userInput << " Invalid option!\ntry again: ";
cin >> userInput;
cout << endl;
}
else if(userInput < answer) {
cout << userInput << " is too low!\ntry again: ";
cin >> userInput;
cout << endl;
}
else if(userInput > answer) {
cout << userInput << " is too high!\ntry again: ";
cin >> userInput;
cout << endl;
}
}
cout << userInput << " is correct!\n\n";
return 0;
}
When you need to deal with user input differently based on some logic, your best option is to:
Read lines of text. Figure out what to do when there is no more input.
Process each line of text using custom logic.
In your case, you could use:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std;
int main() {
// Vaules do not change
const int minNum = 1;
const int maxNum = 100;
int userInput;
// Changes every second
srand(time(0));
// Random number is stored
const int answer = minNum + (rand() % maxNum);
cout << answer << endl; // For testing purposes
std::string line;
cout << "Guess a number 1-100: ";
while ( getline(std:::cout, line ) )
{
// Deal with empty lines.
if ( line.size() == 0 )
{
continue;
}
// If the first character is a letter ...
if(isalpha(line[0])) {
cout << line << "\n Invalid option!\ntry again: ";
continue;
}
// Extract the number from the line using a stringstream.
// If there is a problem extracting the number ...
std::istringstream str(line);
if ( !(str >> userInput ) )
{
cout << line << "\n Invalid option!\ntry again: ";
continue;
}
cout << endl;
// Check the user input against the random answer.
if(userInput == answer) {
cout << "Correct!\n\n";
}
else if(userInput < 1 || userInput > 100 ) {
cout << userInput << " Invalid option!\ntry again: ";
}
else if(userInput < answer) {
cout << userInput << " is too low!\ntry again: ";
}
else if(userInput > answer) {
cout << userInput << " is too high!\ntry again: ";
}
cout << "Guess a number 1-100: ";
}
cout << userInput << " is correct!\n\n";
return 0;
}

C++ Line graph acting funky

I am trying to create a line graph that displays temperatures that have been read from a local file. Currently, everything is working as intended except the graphical output.
Right now, my else statement for the negative numbers is not working correctly. In addition, some numbers appear to be shown and some do not.
Lastly, the numbers that are displaying are not showing the right number of '*". I know I am close but cannot crack the code...
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std
int main()
{
//Variable declarations
int numberOfStars;
int printStars;
int temp;
int count = 0;
string lineBreak = " | ";
ifstream tempData;
tempData.open("tempData.txt");
cout << "Temperatures for 24 hours: " << endl;
cout << " -30 0 30 60 90 120" << endl;
printStars = 0;
while (count < 24) {
tempData >> temp;
if (temp >= 0) {
numberOfStars = temp / 3;
cout << setw(4) << temp << setw(10) << lineBreak;
while (printStars < numberOfStars){
cout << '*';
printStars++;
}
cout << endl << endl;
}
else {
numberOfStars = temp / 3;
while (numberOfStars > printStars) {
cout << '*';
printStars++;
}
cout << setw(4) << temp << setw(10)<< lineBreak << endl << endl;
}
count++;
}
//Closing program statements
system("pause");
return 0;
Currently it is outputting:
Thanks for help in advance.
Oh just put your printStars = 0; in the while :)
And do numberOfStars = temp / 3 + 1; if you want to have one star for temp < 3.
EDIT: You can simplify a lot your code. You can create a string with n time a character very easily. Your code should look like this:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
//Variable declarations
int numberOfStars;
int numberOfSpaces;
int temp;
int count = 0;
string lineBreak = " | ";
ifstream tempData;
tempData.open("data.txt");
cout << "Temperatures for 24 hours: " << endl;
cout << " -30 0 30 60 90 120" << endl;
while (count < 24) {
tempData >> temp;
numberOfStars = temp / 3 + 1;
if (temp >= 0) {
cout << setw(4) << temp << setw(10) << lineBreak;
cout << string(numberOfStars, '*');
}
else {
cout << setw(4) << temp;
numberOfSpaces = 7 + numberOfStars;
// Prevent any ugly shift
if (numberOfSpaces < 0)
{
numberOfSpaces = 0;
numberOfStars = -7;
}
cout << string(7 + numberOfStars, ' ');
cout << string(-numberOfStars, '*');
cout << lineBreak;
}
cout << endl << endl;
count++;
}
//Closing program statements
cin.get();
return 0;
}

Reading letters and numbers from .txt file

I program which reads the letters and numbers from the input being used. But i dont know how to implement this to a .txt file. This is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char ch;
int countLetters = 0, countDigits = 0;
cout << "Enter a line of text: ";
cin.get(ch);
while(ch != '\n'){
if(isalpha(ch))
countLetters++;
else if(isdigit(ch))
countDigits++;
ch = toupper(ch);
cout << ch;
//get next character
cin.get(ch);
}
cout << endl;
cout << "Letters = " << countLetters << " Digits = " << countDigits << endl;
return 0;
}
I made a mistake in my HW I was suppose to count the words instead of letters from the .txt file. Im having trouble counting words because I get confused with the space between words. How could I change this code to count the words instead of letters? I really appreciate the help.
This code counts each word separately. If the first character of a "word" is a number, it assumes the entire word is numeric.
#include <iterator>
#include <fstream>
#include <iostream>
int main() {
int countWords = 0, countDigits = 0;
ifstream file;
file.open ("your_text.txt");
string word;
while (file >> word) { // read the text file word-by-word
if (isdigit(word.at(0)) {
++countDigits;
}
else {
++countWords;
}
cout << word << " ";
}
cout << endl;
cout << "Letters = " << countLetters << " Digits = " << countDigits << endl;
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char ch;
int countLetters = 0, countDigits = 0;
ifstream is("a.txt");
while (is.get(ch)){
if(isalpha(ch))
countLetters++;
else if(isdigit(ch))
countDigits++;
ch = toupper(ch);
cout << ch;
}
is.close();
cout << endl;
cout << "Letters = " << countLetters << " Digits = " << countDigits << endl;
return 0;
}