Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
My program keeps crashing every time I enter an input even though I use a system pause method and displays the same number of vowels and consonants that is incorrect. What's going on?
int main() {
// declare vars
char ch;
int vowels = 0;
int consonants = 0;
string word = "temp";
// prompt user
cout << "Please enter a word: ";
cin >> ch;
// loop vowels and consonants
for (int i = 0; i < word.size(); i++) {
ch = toupper(word[i]);
switch (ch) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowels++;
break;
default:
consonants++;
}
}
// show num of vowels and consanants
cout << "Number of Vowels: " << vowels << endl;
cout << "Number of Consanants: " << consonants << endl;
// pause and exit
getchar();
getchar();
return 0;
}
Normally it's better to input a full string and then parse... but if for some reason you need to stream characters as they are entered you can use cin.get(). make sure to #include <cctype> if you want to use toupper().
char nextChar;
nextChar = cin.get();
nextChar = toupper(nextChar);
int consonants = 0;
int vowels = 0;
int words = 0;
while (nextChar != '\n')
{
switch (nextChar)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowels++:
break;
case ' ':
words++;
break;
default:
consonants++;
break;
}
}
cout << "There were " << consonants << " consonants and " << vowels << " vowels in " << words << " words.";
instead of ending on a newline, if you want to limit to one word simply replace (nextChar != '\n') with (nextChar != ' ').
The only change that needs to occur is the change from:
cin >> ch;
to
cin >> word;
And you code will be fine. Live example
Some chages in your code :
#include <iostream>
#include <string>
using namespace std;
int main() {
// declare vars
char ch;
int vowels = 0;
int consonants = 0;
string word = "temp";
// prompt user
cout << "Please enter a word: ";
cin >> word;
// loop vowels and consonants
for (int i = 0; i < word.size(); i++) {
ch = toupper(word[i]);
switch (ch) {
case 'A':
vowels++;
break;
case 'E':
vowels++;
break;
case 'I':
vowels++;
break;
case 'O':
vowels++;
break;
case 'U':
vowels++;
break;
default:
consonants++;
}
}
// show num of vowels and consanants
cout << "Number of Vowels: " << vowels << endl;
cout << "Number of Consanants: " << consonants << endl;
// pause and exit
getchar();
getchar();
return 0;
}
Okay, so this isn't quite an answer, but it's a bit too detailed to put into a comment...
I just ran your code and it worked fine. I added the following three libraries
#include<string>
#include<iostream>
#include<stdio.h>
And then:
using namespace std;
and then compiled with g++ filename.
Check to make sure you're libraries are up to date and that you're compiling the code correctly.
Hope this helps.
Related
I'm making a game that tests the ASCII strength of a user versus a bot. (There is also a 2 player mode but that's working fine.) The full description is given at the top of my .cpp file. As a basic breakdown, the bot opens a txt file with 500 common four letter words and inserts them into a size 500 array. It then randomly generates a number to pick a random one, and then goes through the process of tovalue() to recieve its ASCII value, where in tovalue() runs through chartoint() four times, one for each character of the word. My issue is that the program calculates the ASCII value perfectly fine of the user generated word, but always returns 0 (0000) for the botword, no matter what the word.
I've tried a few iterations of the generateword() function including using a vector but always get the same resutls. I've done a lot of digging about this and haven't quite found any solutions, although I suspect that the chartoint() function could be better optimized, just not sure how to impliment any better solutions for this specific case. Also, don't think the problem is with chartoint() since it works fine for user input, but I'm pretty sure the problem is with generateword(). Suggestions for making chartoint() would be helpful, but its not my main priority right now since I just need the program to 100% work first. Also, I've confirmed that all of the words in my .txt file are all caps and only four characters per line.
// Write the code for a game called “ASCII Strength” of a four-letter word selected by Player 1
// followed by a four-letter word selected by Player 2. The result would be the sum
//of the ASCII value of each of the letters of the selected words and whoever has higher sum (called ASCII strength) wins.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;;
int chartoint(char a) {
switch (a) {
case 'A':
return 1;
break;
case 'B':
return 2;
break;
case 'C':
return 3;
break;
case 'D':
return 4;
break;
case 'E':
return 5;
break;
case 'F':
return 6;
break;
case 'G':
return 7;
break;
case 'H':
return 8;
break;
case 'I':
return 9;
break;
case 'J':
return 10;
break;
case 'K':
return 11;
break;
case 'L':
return 12;
break;
case 'M':
return 13;
break;
case 'N':
return 14;
break;
case 'O':
return 15;
break;
case 'P':
return 16;
break;
case 'Q':
return 17;
break;
case 'R':
return 18;
break;
case 'S':
return 19;
break;
case 'T':
return 20;
break;
case 'U':
return 21;
break;
case 'V':
return 22;
break;
case 'W':
return 23;
break;
case 'X':
return 24;
break;
case 'Y':
return 25;
break;
case 'Z':
return 26;
break;
}
return 0;
}
int tovalue(string input) {
int first = chartoint(input[0]);
int second = chartoint(input[1]);
int third = chartoint(input[2]);
int fourth = chartoint(input[3]);
cout << first << second << third << fourth; // EXISTS TO TEST CALCULATION
int value = first + second + third + fourth;
return value;
}
string generateword() {
string arr[500];
ifstream file("words.txt");
if (file.is_open())
{
for (int i = 0; i < 500; i++) {
string temp;
getline(file, temp);
arr[i] = temp;
}
file.close();
}
else
{
cout << "Error: Unable to open file.";
exit(0);
}
srand(time(0));
int random_index = rand() % 500;
string random_word = arr[random_index];
return random_word;
}
int main()
{
cout << "Welcome to ASCII strength, a game where the strongest word wins!";
cout << "\nTo play, you must enter a four letter word. The program will calculate the 'ASCII strength' of your word and compare it to your opponent.";
cout << "\nWhoever has the higher sum will win!";
char another;
another = 'y';
while (another == 'y' || another == 'Y') {
cout << "\nWould you like to play against a friend, or against a bot? (F/B)";
char mode;
cin >> mode;
if (mode == 'F' || mode == 'f') {
cout << "\nPlayer 1, please input your four letter word in all caps: ";
string answer1;
cin >> answer1;
int value1;
value1 = tovalue(answer1);
cout << "\nPlayer 2, please input your four letter word in all caps: ";
string answer2;
cin >> answer2;
int value2;
value2 = tovalue(answer2);
if (value1 > value2) {
cout << "\nPlayer 1 wins!";
}
else if (value2 > value1) {
cout << "\nPlayer 2 wins!";
}
else if (value1 == value2) {
cout << "\nTie!";
}
}
else if (mode == 'B' || mode == 'b') {
cout << "\nPlease input your four letter word in all caps: ";
string answer;
cin >> answer;
int valueanswer;
valueanswer = tovalue(answer);
string botword;
botword = generateword();
cout << "\nThe bot generates a random word based on a list of popular four letter words.";
cout << "\nThe bot has generated this word: " << botword;
int valuebot;
valuebot = tovalue("botword");
cout << valueanswer << " " << valuebot; // THIS EXISTS PURELY TO TEST WHETHER THE VALUES ARE PROPERLY CALCULATING
if (valueanswer > valuebot) {
cout << "\nYou win!";
}
else if (valuebot > valueanswer) {
cout << "\nThe bot wins!";
}
else if (valueanswer == valuebot) {
cout << "\nTie!";
}
}
cout << "\nWould you like to start a new game? (y/n)";
cin >> another;
}
}
Your problem is this line:
valuebot = tovalue("botword");
Since all characters in "botword" are lowercase, you get all 0 score. You probably meant to write
valuebot = tovalue(botword);
I'm having trouble converting using toupper on the first character in my string.
I used tolower(first[0]) to turn the first letter into lower case.
Why doesn't toupper(first[0]) make the first character upper case?
Also, is there a way to move the first character in a string to the last spot?
Thanks a lot in advance.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char ans;
do{
string first, last;
char first_letter, first_letter2;
cout << "This program will convert your name "
<< "into pig latin.\n";
cout << "Enter your first name: \n";
cin >> first;
cout << "Enter your last name: \n";
cin >> last;
cout << "Your full name in pig latin is ";
for(int x = 0; x < first.length(); x++){
first[x] = tolower(first[x]);
}
for(int x = 0; x < last.length(); x++){
last[x] = tolower(last[x]);
}
first_letter = first[0];
bool identify;
switch (first_letter)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
identify = true;
break;
default:
identify = false;
}
if(identify == true){
toupper(first[0]);
cout << first << "way" << " ";
}
first_letter2 = last[0];
bool identify2;
switch (first_letter2)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
identify2 = true;
break;
default:
identify2 = false;
}
if(identify2 == true){
toupper(first[0]);
cout << last << "way" << endl;
}
cout << "You you like to try again? (Y/N)\n";
cin >> ans;
} while(ans == 'y' || ans == 'Y');
return 0;
}
Just a simple blunder, compare
first[x] = tolower(first[x]);
with
toupper(first[0]);
usual case of the 'can't see the obvious thing missing' syndrome... I hate those mistakes.
As for moving the first character to the end I'd usually just use substr() for a simple case:
str = str.substr(1) + str[0];
I'm trying to make my C++ program exit.
I know I can pause input with while cin >> s, but I don't know what to do to make the entire program exit.
This is my code:
int main()
{
long int l;
long int i;
char s[100000];
while (cin >> s)
{
l = strlen(s);//strlen Returns the length of the C string str.
for (i = 0; i<l; i++)
{
switch (s[i])
{
case 'W':
cout << "Q"; break;
case 'E':
cout << "W"; break;
case 'R':
cout << "E"; break;
default:
cout << ";"; break;
}
}
cout << (" ");
}
system("pause");
return 0;
}
Your program will terminate when it runs out of input.
The system("pause"); seems to imply that you're using Microsoft Windows. To signal an end-of-file condition for keyboard input on Windows, type Ctrl-Z. (For Linux and other Unix-like systems, use Ctrl-D at the beginning of a line.)
Incidentally, the program you posted is complete and will not compile. That can be corrected by adding the following lines to the top:
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
When posting a question, please include the entire program.
I was able to get the program to exit by using the command exit(0); within the while loop.
Here is my finished program:
include iostream
include string
using namespace std;
int main(){
long int l;
long int i;
char s[100000];
cout << "\n Write your code in UpperCase, "
cout << "to close the program switch to LowerCase \n" << endl;
while (cin >> s)
{
l = strlen(s);//strlen Returns the length of the C string str.
for (i = 0; i<l; i++)
{
switch (s[i])
{
case 'W':
cout << "Q"; break;
case 'E':
cout << "W"; break;
case 'R':
cout << "E"; break;
default:
exit(0); break;
}
}
cout << (" ");
}
system("pause");
return 0;
}
Your loop is waiting until cin >> s returns an "end of file" (EOF). You can accomplish this on Windows by typing Ctrl+Z or on Unix-like systems such as Mac and Linux Ctrl+D.
You could also put a break character in your loop, or change the condition altogether.
#include <iostream>
using namespace std;
int main()
{
int grade;
int aCount;
int bCount;
int cCount;
int dCount;
int fCount;
cout << "Enter the letter grades." << endl
<< "Enter the EOF character to end input." << endl;
while ((grade = cin.get()) != EOF)
{
switch (grade)
{
case 'A':
case 'a':
aCount++;
break;
case 'B':
case 'b':
bCount++;
break;
case 'C':
case 'c':
cCount++;
break;
case 'D':
case 'd':
dCount++;
break;
case 'F':
case 'f':
fCount++;
break;
case '\n':
case '\t':
case ' ':
break;
default:
cout << "Incorrect letter grade entered." << "Enter a new grade." << endl;
break;
}
}
cout << "\n\nNumber of students who received each letter grade:"
<< "\nA: " << aCount
<< "\nB: " << bCount
<< "\nC: " << cCount << "\nD: " << dCount << "\nF: " << fCount << endl;
system("PAUSE");
return 0;
}
This is an exact code provided by my C++ textbook. While I was practicing these switch statement codes by copying these codes then compile it, my Visual Studio 2010 express keep gives me an error saying that "aCount is being used without assigned..." same applies to fCount. This program should read any letter from A to F from a keyboard then increment whatever letter that was recognized. I think there should be cin>>grade somewhere in the codes but I don't find it. By the way, can "cin.get()" could work as cin>>grade??
When you are declaring your variables try giving them the value of 0 like this:
int grade = 0;
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
This will ensure that you are in fact assigning a value to the variable before it is being used.
Then try to run it, I bet it works!
It is advisable for you to initialize your variables being using it. Some compiler will not even give you a warning before compilation, but assigns some "garbage values" to your un-initialize variables.
Initializing your variables to 0 is suffice in this scenario (Like what other user mentioned).
int grade=0;
int aCount=0;
int bCount=0;
int cCount=0;
int dCount=0;
int fCount=0;
By the way, can "cin.get()" could work as cin>>grade??
That depends on how you want to use it. cin.get can be used to extract a:
single character
multiple characters and store them as c-string (char array) or
store them into a stream buffer object
from the input stream.
You may realize cin.get can't accept numbers, so if you are accepting input of characters or string, it is fine. But in future, if you want it to accept numbers, just use cin >> number
An example on using cin.get()
char cStr[50];
cin.get(cStr,5); //It will take n-1 characters
cout << cStr;
//Input: abcde
//Output: abcd
I am having trouble with my program, there's something wrong in how it counts vowels and consonants
#include<iostream>
using namespace std;
int main(){
int num[10],even = 0,odd = 0;
char choice;
int vowelcount = 0;
int concount = 0;
string word;
cout<<"MENU:"<<endl<<"[N]umber"<<endl<<"[L]etter"<<endl<<"Choice : ";
cin>>choice;
switch(choice){
case 'n': case 'N':
cout << "Enter 10 integers: \n";
for(int i = 0; i < 10; i++) {
cin >> num[i];
if((num[i] % 2) == 0) {
even++;
}
}
odd = 10 - even;
cout << "Even: " << even << endl;
cout << "Odd: " << odd << endl;
system("pause");
cout<<"Do you want to repeat the program ? Y/N ";
break;
case 'l': case 'L':
cout<< "Enter 10 Letters : \n";
cin>> word;
for (int i=0; word [i] != '\0'; i++){
word[i] = tolower (word[i]);
for (int i=0; word [i] != '\0'; i++)
switch(choice){
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' :
vowelcount++;
break;
default:
concount++;
}
}
cout<<" total vowels = " <<vowelcount << endl;
cout<<" total consonant = " <<concount << endl;
system("pause");
return 0;
}
}
Okay, several problems here. First off, always try to give more information then 'there is something wrong'. I simply copied your example in to visual studio and was pretty quickly able to figure out your problems, but with more information I probably wouldn't have needed to do this. Also, there's no need for the entire question to be uppercase. :)
So... your switch statement is being done on a variable called choice. This variable is the one that you're using to select your menu option. You need to be running your switch statement on the character you're testing. Also, you've got two loops and you only need the one.
Right now, because you're running the program on choice and you have two loops, each time through each loop choice is always 'l' or 'L' which are consonants, but it's being run a number of times equal to the length of the input string squared. So your response is 0 for the number of vowels, because it never sees any, and the length of your input string squared because you have the nested loops and it's counting 'L' that many times.
Instead of using a switch statement, you could use a string and the std::string::find method:
std::string vowels = "AEIOUaeiou";
std::string consonants = "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz";
if (vowels.find(letter) != std::string::npos)
{
++vowelcount;
}
else
{
if (consonants.find(letter) != std::string::npos)
{
++consonantcount;
}
}