"Truncation from int to char" not producing any result - c++

My code can compile but it doesn't return the character asked and it also does not follow the else statement since it will cout the error message after any input from the true if statement. Beginner in C++ so any help is appreciated.
// Python Challenge 2.cpp : This program will take a line of text from the user and then translate each letter 2 over in the alphabet.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
char chChar;
char chChar2;
char chChar_a;
char chChar_b;
int main()
{
//This takes the one letter input from the user:
cout << "Type in a lowercase letter: ";
cin >> chChar;
//for letters a-x
if ((int)chChar >= 97 && (int)chChar <= 120)
char chChar2 = (int)chChar + 2;
cout << "is now: " << chChar2 << endl;
//for the letter y
if ((int)chChar == 121)
{
char chChar_a = '97';
cout << "is now: " << chChar_a << endl;
}
//for the letter z
if ((int)chChar == 122)
{
char chChar_b = '98';
cout << "is now: " << chChar_b << endl;
}
//for everything else
else
cout << "Error: type in a lowercase letter." << endl;
return 0;
}

Your if statement is not correct: you forgot to create a block using { } after it.
As it stands, the code does:
//for letters a-x
if ((int)chChar >= 97 && (int)chChar <= 120)
{
char chChar2 = (int)chChar + 2;
}
// Always runs the next part
cout << "is now: " << chChar2 << endl;
...
And the final else is attached to the if before it:
//for the letter z
if ((int)chChar == 122)
{
char chChar_b = '98';
cout << "is now: " << chChar_b << endl;
}
else
{
cout << "Error: type in a lowercase letter." << endl;
}
To fix this, add the proper brackets { }. An if without the brackets only conditionally executes the next statement, and not the block -- don't let indentations fool you: they have no meaning in C.
So, with this, your fixed code should look like:
//This takes the one letter input from the user:
cout << "Type in a lowercase letter: ";
cin >> chChar;
//for letters a-x
if ((int)chChar >= 97 && (int)chChar <= 120)
{
char chChar2 = (int)chChar + 2;
cout << "is now: " << chChar2 << endl;
//for the letter y
if ((int)chChar == 121)
{
char chChar_a = '97';
cout << "is now: " << chChar_a << endl;
}
//for the letter z
if ((int)chChar == 122)
{
char chChar_b = '98';
cout << "is now: " << chChar_b << endl;
}
}
//for everything else
else
{
cout << "Error: type in a lowercase letter." << endl;
}
return 0;
Starting from this, you can debug your code for further issues.

Related

Character count ignoring first characters in multiple strings

#include <iostream>
using namespace std;
int main()
{
string sentence;
int countv = 0, countc = 0, countspace = 0, number, s = 1;
cout << "How many sentence would you like to check? - ";
cin >> number;
while(s <= number)
{
cout << "\nSentence " << s << ":";
cin.ignore();
getline(cin, sentence);
for(int i = 0; i < sentence.length(); i++)
{
if(sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u')
countv++;
else if(isspace(sentence[i]))
countspace++;
else
countc++;
}
cout << "\nSentence " << s << " result:";
cout << "\nThere are " << countv << " vowels in the sentence.";
cout << "\nThere are " << countc << " consonants in the sentence.";
cout << "\nThere are " << countspace << " whitespace in the sentence.";
countc = 0, countv = 0, countspace = 0;
s++;
cout << "\n";
}
}
I'm trying to count the number of vowels and consonants in multiple strings but, for some reason, it only gives the correct output for the first string.
I've noticed that, for the next strings (2nd, 3rd and so on), it does not count the first letter of the string. Why is this?
The code is ignoring the first character of each of the strings after the first because you are telling it to ignore those on input … with the call to cin.ignore(). That call should not be inside the loop but immediately before it, so as to ignore the newline that is left in the input stream after the cin >> number extraction.
Note that the call to getline does not leave that newline in the stream's buffer; see this cppreference page:
… the next available input character is delim, as tested by
Traits::eq(c, delim), in which case the delimiter character is
extracted from input, but is not appended to str.
Here's a suitably modified version of your code:
#include <string>
#include <iostream>
using std::cin, std::cout;
int main()
{
std::string sentence;
int countv = 0, countc = 0, countspace = 0, number, s = 1;
cout << "How many sentence would you like to check? - ";
cin >> number;
cin.ignore(); // Call ignore HERE (once) to skip the newline left in the buffer from the above!
while (s <= number)
{
cout << "\nSentence " << s << ":";
// cin.ignore(); WRONG!
std::getline(cin, sentence);
for (size_t i = 0; i < sentence.length(); i++)
{
if (sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u')
countv++;
else if (isspace(sentence[i]))
countspace++;
else
countc++;
}
cout << "\nSentence " << s << " result:";
cout << "\nThere are " << countv << " vowels in the sentence.";
cout << "\nThere are " << countc << " consonants in the sentence.";
cout << "\nThere are " << countspace << " whitespace in the sentence.";
countc = countv = countspace = 0; // Nicer than the dodgy use of the comma!
s++;
cout << "\n";
}
}

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

Switch statement to evaluate string input C++

I am working with a user entered string input and I need to use switch-statements to evaluate each of the entered input. My code below currently evaluates a users string input and looks to see if it is a upper case, number, or special character using ASCII codes. I am now sure how switch-statements work and how I could change an If statement to a switch-statement.
for (int i = 0; i < strlength; i++) //for loop used to check the rules of the password inputted by the user
{
cout << "Testing for upper case characters..." << endl; //displays the cout
tmpi=(int) str1[i]; //stoi function making the string input an integer
if ((tmpi >= 65) && (tmpi <= 90)) //checks if there are two upper case characters in the string
{
cout << "Found an uppercase" << endl;
uppercnt++; //adds to the counter of upper case
state++;
cout << "Now in state q" << state << "..." << endl;
continue;
}
cout << "Testing for digits..." << endl;
if(tmpi >= 48 && tmpi <= 57) //checks if there are two digits in the string
{
cout << "Found a digit" << endl;
digitcnt++; //adds to the counter of digit
state++;
cout << "Now in state q" << state << "..." << endl;
continue;
}
cout << "Testing for special characters..." << endl;
if(tmpi >= 33 && tmpi <= 47 || tmpi >= 58 && tmpi <= 64 || tmpi >= 91 && tmpi <= 96 || tmpi >= 123 && tmpi <= 126) //checks if there are special characters
{
cout << "Found a special char" << endl;
speccnt++; //adds to the counter of special character
state++;
cout << "Now in state q" << state << "..." << endl;
continue;
}
cout << "Character entered was a lower case" << endl;
state++;
cout << "Now in state q" << state << "..." << endl;
} //end for loop
Any advice or examples would help out, thanks.
if perfomance not an issue, I just would use std::count_if:
int upps = std::count_if( pass.begin(), pass.end(), isupper );
int digs = std::count_if( pass.begin(), pass.end(), isdigit );
working example on ideone

If and else Statements in While loop" for C++

I have a question regarding if & else statements in a while loop.
I wanted to establish a few things in my program:
wanted user to only input 4 letter characters without the use of numbers and symbols.
converting each those letters into ints(Ascii val.)
To make it easier to understand if confused,
Program 1st asks for 4 letter word.
User places input. If input contains at least:
a non-letter character, then Program asks User for new Input.
If input only contain letters Program checks input for # of letters.
If input doesn't have ___ :
4 letters, Program asks User for new Input.
Otherwise Program proceeds with determining Int value of each letter
Okay so heres my Program so far: ** not sure if this correct for
#include <iostream>
using namespace std;
int main() {
string input;
int input0 = input[0];
int input1 = input[1];
int input2 = input[2];
int input3 = input[3];
cout << "\nEnter a 4-letter word (Keep it clean!).\n";
while(cin>>input){
cout << endl << input << " has " << input.length() << " letters." << endl;
if (int(input[0]) > 64 || int(input[0]) < 91 || int(input[0]) > 96 || int(input[0]) < 123 ||
int(input[1]) > 64 || int(input[1]) < 91 || int(input[1]) > 96 || int(input[1]) < 123 ||
int(input[2]) > 64 || int(input[2]) < 91 || int(input[2]) > 96 || int(input[2]) < 123 ||
int(input[3]) > 64 || int(input[3]) < 91 || int(input[3]) > 96 || int(input[3]) < 123) {
if (input.length()!=5 && input.length()>3)
cout << "\n the int value of the " << input[0] << " is " << int(input[0]) << endl;
cout << "\n the int value of the " << input[1] << " is " << int(input[1]) << endl;
cout << "\n the int value of the " << input[2] << " is " << int(input[2]) << endl;
cout << "\n the int value of the " << input[3] << " is " << int(input[3]) << endl;
else cout << input << "is not a 4-letter word.\nPlease try again." << endl;
}
else cout << input << " contains number(s) and or symbol(s).\nPlease try again." << endl;
}
}
I got 2 errors:
error: expected '}' before 'else'
error: 'else' without a previous 'if'
This fairly gnarly bunch of statements is to blame:
if (input.length()!=5 && input.length()>3)
cout << "\n the int value of the " << input[0] << " is " << int(input[0]) << endl;
// Not part of if-statement:
cout << "\n the int value of the " << input[1] << " is " << int(input[1]) << endl;
cout << "\n the int value of the " << input[2] << " is " << int(input[2]) << endl;
cout << "\n the int value of the " << input[3] << " is " << int(input[3]) << endl;
else cout << input << "is not a 4-letter word.\nPlease try again." << endl;
You need to enclose all those cout statements (up until the else) in braces {, }.
I'd just like to make a point about the character tests you're doing. It looks like you're checking whether the characters are letters, but are using the least-readable, least-portable approach. Use std::isalpha instead. In fact, you can accomplish the whole thing with this:
if( std::all_of( input.begin(), input.begin() + 4, [](char c){ return (bool)isalpha(c); } ) )
{
//...
}
You should do the tests after ensuring the input is the correct length, or you will have undefined behaviour. So let's do that:
while( cin>>input )
{
cout << endl << input << " has " << input.length() << " letters." << endl;
if( input.length() != 4 )
{
cout << input << "is not a 4-letter word.\nPlease try again." << endl;
}
else if( any_of( input.begin(), input.end(), [](char c){ return !isalpha(c); } ) )
{
cout << input << " contains number(s) and or symbol(s).\nPlease try again." << endl;
}
else
{
// I assume you want to exit the loop here.
break;
}
}
Notice I flipped the all_of statement around to the inverse ("any character is not a letter"), for better readability because the lambda no longer needs a cast for automatic type-deduction:
if( any_of( input.begin(), input.end(), [](char c){ return !isalpha(c); } ) ) ...

C++ program to display votes in percentage not showing correct result

I'm solving some C++ problems from ebooks. I made this C++ program but it isn't working properly. I've 2 problems:
Even after applying the forumla (votePercentage = firstAnswer/totalVotes*100;) it isn't showing the output, but only 0.
The program should display the bar chart, how am I suppose to do that? Any hints, reference or solution will be appreciated.
Here is my code:
/*
* Write a program that provides the option of tallying up the
* results of a poll with 3 possible values.
* The first input to the program is the poll question;
* the next three inputs are the possible answers.
* The first answer is indicated by 1, the second by 2, the third by 3.
* The answers are tallied until a 0 is entered.
* The program should then show the results of the poll—try making
* a bar graph that shows the results properly scaled to fit on
* your screen no matter how many results were entered.
*/
#include <iostream>
#include <string>
void startPoll (void);
void showPoll (void);
void pollCheck (void);
std::string pollQuestion, answer1, answer2, answer3;
int pollChoice, firstAnswer, secondAnswer, thirdAnswer;
int main (void)
{
int totalVotes = 1;
float votePercentage;
startPoll();
showPoll();
for(;;totalVotes++)
{
if (pollChoice == 1)
{
firstAnswer = firstAnswer + 1;
}
else if (pollChoice == 2)
{
secondAnswer++;
}
else if (pollChoice == 3)
{
thirdAnswer++;
}
else
{
std::cout << "==============*======*======*==============\n"
<< " RESULT \n"
<< "==============*======*======*==============\n"
<< "Question: " << pollQuestion << "\n"
<< "Total Votes: " << totalVotes << "\n";
votePercentage = (firstAnswer/totalVotes)*100;
std::cout << answer1 << ": " << firstAnswer << " votes. | " << votePercentage << "\n";
votePercentage = secondAnswer/totalVotes*100;
std::cout << answer2 << ": " << secondAnswer << " votes. | " << votePercentage << "\n";
votePercentage = thirdAnswer/totalVotes*100;
std::cout << answer3 << ": " << thirdAnswer << " votes. | " << votePercentage << "\n";
return 0;
}
std::cout << "\nEnter your vote again\nOR\nuse 0 to show the results.\n";
std::cin >> pollChoice;
}
std::cout << "Error: Something went wrong!\n";
}
void startPoll (void)
{
std::cout << "Enter your poll question:\n";
getline (std::cin, pollQuestion, '\n');
std::cout << "Enter answer 1:\n";
getline (std::cin, answer1, '\n');
std::cout << "Enter answer 2:\n";
getline (std::cin, answer2, '\n');
std::cout << "Enter answer 3:\n";
getline (std::cin, answer3, '\n');
}
void showPoll (void)
{
std::cout << "==============|======|======|==============\n"
<< " POLL \n"
<< "==============|======|======|==============\n"
<< pollQuestion << "\n"
<< "1. " << answer1 << "\n"
<< "2. " << answer2 << "\n"
<< "3. " << answer3 << "\n\n"
<< "Enter 1,2 or 3:\n\n";
std::cin >> pollChoice;
pollCheck();
}
void pollCheck (void)
{
if (pollChoice != 1 && pollChoice != 2 && pollChoice != 3)
{
std::cout << "Wrong choice entered! Please try again.\n\n";
return showPoll();
}
}
You need to take care that integer/integer = integer. In your case, changing
(firstAnswer/totalVotes)*100
to
(1.0*firstAnswer/totalVotes)*100
or
(firstAnswer*100.0/totalVotes)
should work. They all give a floating point result.
Well, the solution for the Bar Chart could be the following:(Not written by me) I think thats very self explaining because its really basic
void line (int n, char c)
{
// this is the loop for n
for (int i = 0; i < n; i++)
cout << c << endl;
}
Here is my solution, you can see how I made the bars work by reading the comments.
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 0;
int c = 0;
cout << "What is your favorite animal? 1 Cat, ";
cout <<"2 Dog, 3 Fish, 0 Count votes" << endl;
//Choice counter
while (true)
{
int choice;
cout << "Choice: ";
cin >> choice;
if(choice == 1)
a++;
else if(choice == 2)
b++;
else if(choice == 3)
c++;
else if(choice == 0)
break;
else
continue;
}
cout << endl << " 1: " << a << endl;
cout << " 2: " << b << endl;
cout << " 3: " << c << endl;
cout << endl << "1\t" << "2\t" << "3\t" << endl;
//Finds the max voted option
int max = 0;
if(a > b && a > c)
max = a;
else if(b > c && b > a)
max = b;
else if(c > a && c > b)
max = c;
/* If the max voted option is bigger than 10, find by how much
we have to divide to scale the graph, also making 10 bar
units the max a bar can reach before scaling the others too */
int div =2;
if(max > 10)
{
do
{
max = max/div;
if(max < 10)
break;
div++;
}while(true);
}else
div = 1;
//Sets the final number for the bars
a=a/div;
b=b/div;
c=c/div;
if(a==0)
a++;
if(b==0)
b++;
if(c==0)
c++;
//Creates the bars
while(true)
{
if(a>0)
{
cout << "[]" << "\t";
a--;
}else
cout << " ";
if(b>0)
{
cout << "[]" << "\t";
b--;
}else
cout << " ";
if(c>0)
{
cout << "[]" << "\t";
c--;
}else
cout << " ";
cout << endl;
if(a==0 && b==0 && c==0)
break;
}
}