Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 months ago.
Improve this question
So in this small project for my school I needed to build a word guessing game everything works fine except the string university which always gives output incorrect, I tried changing it to universit and it works but university doesn't work. I cant figure out what the problem is.
Also are there any other alternatives to strcmp()?
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{ // at first we are basically going to give an intro to the gameseco
cout << " HANGMAN : GUESS THE WORD AND NOT DIE!!\n\n\n";
cout << " Welcome to the game player!!\n\n";
cout << " Rules: Guess the word by typing a letter based on given hints.\n";
cout << " Multiple incorrect guesses will HANG YOU.\n\n";
// here we add different words in the game for the guessing system using a 2 dimensional array
char word[20][20] = {
"higher",
"secondary",
"first",
"year",
"cotton",
"university",
"computer",
"science",
"project",
"hangman",
};
char newword[20], guess[10];
bool again = 1;
while (again == 1)
{
again = 0;
srand(time(0));
int x = 0, wrong = 0, z = (rand() % 10) + 0;
strcpy(newword, word[z]); // so we used strcpy command to copy an element of the 2D array of randomly generated index to a new string
cout << "Enter your guess. \nHINT: Word Length(indicated by underscores) = "; // hint no. one the gives us the exact lenth of word
for (x = 0; newword[x] != '\0'; x++)
{
cout << "-";
}
cout << "\nWord starts with: '" << newword[0] << "'"; // hint no. two which gives the player an idea what the word might be
cout << "\n\n";
for (wrong = 1; wrong <= 6; wrong++) // the loop here checks whether the input given by the user is correct or not
{
cin >> guess; // the input is taken here
if (strcmp(guess, newword) == 0) // the input is compared with the word to be guessed
{ // using the strcmp() function from the string.h library
cout << "Correct!\n"; // if the guess is correct the program will print correct and correct and end
break; // correct guess will terminate the loop
}
else if (wrong == 1)
{
cout << "Opps! Wrong guess!\n\n"; // if player inputs wrong word a poll will appear for hanging the person
cout << "I=-=\n";
cout << "|\n";
cout << "|\n";
cout << "|\n";
cout << "|\n";
cout << "I\n";
}
else if (wrong == 2)
{
cout << "Opps! Wrong guess again!\n\n"; // each wrong word will result in the appearance of of a hanging person
cout << "I=-=\n";
cout << "| |\n";
cout << "|\n";
cout << "|\n";
cout << "|\n";
cout << "I\n";
}
else if (wrong == 3)
{
cout << "Opps! Wrong guess again!\n\n";
cout << "I=-=\n";
cout << "| |\n";
cout << "| O\n";
cout << "|\n";
cout << "|\n";
cout << "I\n";
}
else if (wrong == 4)
{
cout << "Opps! Wrong guess again!\n\n";
cout << "I=-=\n";
cout << "| |\n";
cout << "| O\n";
cout << "I--|--\n";
cout << "|\n";
cout << "I\n";
}
else if (wrong == 5)
{
cout << "Opps! Wrong guess again!\n\n";
cout << "I=-=\n";
cout << "| |\n";
cout << "| O\n";
cout << "I--|--\n";
cout << "| o\n";
cout << "I\n";
}
else if (wrong == 6)
{
cout << "Opps! Wrong guess again!\nLast Chance!!\n\n"; // unfortunately the player couldn't guess the word
cout << "I=-=\n";
cout << "| |\n";
cout << "| O\n"; // the hanging person compeletely appears and the program ends
cout << "|--|--\n";
cout << "| o\n";
cout << "I | |\n";
cout << "YOU ARE DEAD HAHAHA!!!";
}
}
cout << "Do you want to play again?\nPress 1 for yes, 0 for no."; // here it is asked if we want to play again
cin >> again;
}
return 0;
}
The problem seems to be this declaration:
char guess[10];
Your array declaration should always cater for a \0 character at the end of string. The length of "university" is 10 character, to hold the entire string you required an array of 11 characters.
So please change the length of guess array to be longest string length plus 1.
char guess[11];
As a side note:
Since you are using C++, you should fully utilize the facilities offers by the language. In C++, you should use std::string to store array of characters, use std::vector to store a collection of objects etc.
Related
Here is what I have done so far, I did my best to label each bit of the code. It should also be noted that this was written in XCode, so it's running on a Mac.
/*
Ayush Sharma
4 November 2016
*/
#include <iostream>
#include <ctime>
using namespace std;
int main (){
//clearing the screen
system("clear");
//seeding the random
srand((unsigned int)time(NULL));
//variables & arrays
char answer;
int r, m, correct = 0;
string capitals[50] =
{"Montgomery", "Juneau", "Phoenix", "Little Rock", "Sacramento", "Denver", "Hartford", "Dover", "Tallahassee", "Atlanta", "Honolulu", "Boise", "Springfield", "Indianapolis", "Des Moines", "Topeka", "Frankfort", "Baton Rouge", "Augusta", "Annapolis", "Boston", "Lansing", "St. Paul", "Jackson", "Jefferson City", "Helena", "Lincoln", "Carson City", "Concord", "Trenton", "Santa Fe", "Albany", "Raleigh", "Bismarck", "Columbus", "Oklahoma City", "Salem", "Harrisburg", "Providence", "Columbia", "Pierre", "Nashville", "Austin", "Salt Lake City", "Montpelier", "Richmond", "Olympia", "Charleston", "Madison", "Cheyenne"};
string states[50] = {"Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"};
//title
cout << "***************************************************************\n";
cout << "* *\n";
cout << "* United States Capitals Quiz *\n";
cout << "* *\n";
cout << "***************************************************************\n\n";
for (int i = 0; i < 15; i++){
//Picking A Random State
r = rand() % 50;
//Checking if State is a Repeat
if (states[r] != "-1") {
cout << "What is the capital of " << states[r] << "? ";
//Picking Correct Answer Choice and Respective Layout
m = rand() % 4;
if (m == 0) {
cout << "\nA: " << capitals[r] << endl;
cout << "B: " << capitals[rand()%50] << endl;
cout << "C: " << capitals[rand()%50] << endl;
cout << "D: " << capitals[rand()%50] << endl;
}
if (m == 1) {
cout << "\nA: " << capitals[rand()%50] << endl;
cout << "B: " << capitals[r] << endl;
cout << "C: " << capitals[rand()%50] << endl;
cout << "D: " << capitals[rand()%50] << endl;
}
if (m == 2) {
cout << "\nA: " << capitals[rand()%50] << endl;
cout << "B: " << capitals[rand()%50] << endl;
cout << "C: " << capitals[r] << endl;
cout << "D: " << capitals[rand()%50] << endl;
}
if (m == 3) {
cout << "\nA: " << capitals[rand()%50] << endl;
cout << "B: " << capitals[rand()%50] << endl;
cout << "C: " << capitals[rand()%50] << endl;
cout << "D: " << capitals[r] << endl;
}
//Recieving Answer
cout << "Answer: ";
cin >> answer;
//Converting Letter to Number
if (answer == 'A' || answer == 'a') answer = 0; if (answer == 'B' || answer == 'b') answer = 1;
if (answer == 'C' || answer == 'c') answer = 2; if (answer == 'D' || answer == 'd') answer = 3;
//Comparing Answer to Correct Answer
if (m == answer) {
cout << "Correct!" << endl << endl;
correct++;
}else{
cout << "Incorrect! The correct answer was " << capitals[r] << "! \n\n";
}
//Removing State from Array
states[r] = "-1";
}else{
//If State was a Repeat, generate another State
i--;
}
}
//Printing Results
cout << "Number Correct: " << correct << "/15 or " << ((correct/15.00)*100) << "%!\n";
return 0;
}
The code works, almost. The problem is that answers are sometimes being repeated, such as in the scenario:
What is the capital of Wisconsin?
A. Madison
B. Frankfort
C. Jackson
D. Madison
Only A or D is the "correct" answer despite both having the same text (altough I'd rather make it impossible for the answers to repeat). I also would like to know if there is a more efficient way to create the layout of multiple choice questions. Thanks in advance!
-Ayush
Given that there are 50 values you want to draw from at random, without repetition, simply create an array or vector containing those values, shuffle it, and then access the elements of the shuffled array in order.
In C++11, this is easy using algorithms std::iota() and std::random_shuffle() from <algorithm>.
int value[50];
std::iota(std::begin(value), std::end(value), 0); // populate array with values 0 to 49
std::random_shuffle(std::begin(value), std::end(value));
Then in your outer loop, instead of r = rand()%50 use r=value[i].
std::begin() and std::end() are in standard header <iterator>.
The same idea can be used before C++11, but the method is a little different (C++11 didn't support std::begin(), std::end() or std::iota(), but equivalents are easy enough to implement).
Instead of value being an array, I'd create it as an std::vector<int>, also with 50 elements. I've illustrated above using an array, since you seem to be defaulting to using an array.
That's a pretty obvious thing to happen. An easy solution would be to make an array to hold the options already displayed. Use a while loop to add unique options to the array.You could check whether there is any repetition in the array using another function. Then, display capitals[r] along with three other options from the array.
bool noRepeat(int arr[], int o){
for(int i=0; i<3; i++){
if(arr[i] == o)
return false;
}
return true;
}
int main(){
...
//picking correct answer and determining layout
int m = rand()%4, n=0, y, options[3];
if (m == 0) {
while(n<3){
y = rand()%50;
if(noRepeat(options, y) && capitals[y]!=capitals[r])
options[n++] = y;
}
//display according to layout
cout << "\nA: " << capitals[r] << endl;
cout << "B: " << capitals[options[0]] << endl;
cout << "C: " << capitals[options[1]] << endl;
cout << "D: " << capitals[options[2]] << endl;
}
//do the same for the rest
...
}
Just like #Isaiah said you can use a while loop to test for the index generated to not be same your correct answer.
Something like :
int index = rand() % 50;
while(index == r)
{
index = rand() % 50;
}
cout << "B: " << capitals[index] << endl;
NOTE: this still can produce repeats of "incorrect answers", but i guess you get the point to avoid the repeats produced by rand. And obviously this is code is just to correct the repeats of corrects answer, you should be using rand at all as mentioned in comments by others.
Your problem is to pick three random capitals without repeats. So here's some pseudo code.
Put all capitals, except the true answer into a vector
Generate a random index into this vector
Use the capital at that index, and erase the capital from the vector
Repeat Steps 2 and 3 for the second and third random capitals. Note the random index should allow for the reduced vector size on each iteration.
This question already has answers here:
if statement not working right?
(5 answers)
Closed 6 years ago.
I can't quite figure this out. The program builds no problem. The issue is that no matter what the user input is, the if statement goes ahead and the program does not check the else if statement. I assume there's a larger structural problem in my script, but I'm not sure what it is.
It could be a problem with the find function. I'm still new to this function.
It could also be to do with how I'm nesting this new if-else-if statement within another if statement.
The problem comes towards the end of the code, in the final if-else-if. I'm pasting the whole thing in case it's a deeper issue elsewhere in the code. The previous if statement works fine. Here's the specific piece of code with the problem:
if (song.find(str2)){
cout << "Thank you! I, personally, love this song.\n";
cout << "I probably wouldn't listen to you if you asked me to turn it off.\n";
Sleep(20000);
}
else if (song.find(str3)){
cout << "It's not coming off, " << name <<"." << endl;
}
Thanks for any help. Much appreciated :)
Here's the full code:
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int emotion;
void Sleep()
{
Sleep();
}
void loneliness()
{
cout << "Lonely. You must be strong, and loved, if you choose this feeling to explore.";
}
void inlove()
{
cout << "In love. You've been watching telenovelas again.";
}
void ambitious()
{
cout << "Ambitious. Steve Jobs Steve Jobs.";
}
void happy()
{
cout << "Happy. Is this a thing you can just feel?";
}
int main() {
string input;
string input2;
string name;
cout << "I'm bad." << endl;
cout << "My name's Raab." << endl;
cout << "Your name?" << endl;
getline(cin, name);
cout << "Tell me in one word what emotion you're feeling right now." << endl;
getline(cin, input);
cout << "Haha. " << input << "?" << " " << "Alright. I can work with that." << endl;
cout << "..." << endl;
cout << "Okay, I'm going to give you a choice." << endl;
cout << "You can trade that emotion for one other, if you'd like." << endl;
cout << "Would you like to do that?" << endl;
getline(cin, input2);
if (input2 == "Yes" && "yes") {
int emotion;
cout << "Nice one, bro.\n";
Sleep(350);
cout << "Here are your options!\n";
Sleep(300);
cout << "1. Lonely\n";
cout << "2. In love.\n";
cout << "3. Ambitious.\n";
cout << "4. Happy.\n";
cin >> emotion;
switch (emotion) {
case 1:
loneliness();
break;
case 2:
inlove();
break;
case 3:
ambitious();
break;
case 4:
happy();
break;
}
cin.get();
}
else if (input2 == "No" && "no")
{
std::string song;
std::string str2 ("like");
std::string str3 ("off");
cout << "Well" << endl;
Sleep(250);
PlaySound(TEXT("whip"), NULL, SND_ASYNC|SND_FILENAME);
cout << "." << endl;
Sleep(300);
PlaySound(TEXT("whip"), NULL, SND_ASYNC|SND_FILENAME);
cout << "." << endl;
Sleep(300);
PlaySound(TEXT("whip"), NULL, SND_ASYNC|SND_FILENAME);
cout << "." << endl;
Sleep(300);
PlaySound(TEXT("gravity"), NULL, SND_ASYNC|SND_FILENAME);
Sleep(2500);
cout << "Here we go. You like this song? Or do you want me to turn it off?\n";
Sleep(2000);
cout <<"Wait.\n";
Sleep(2000);
cout << "Don't tell me yet. I'm grooving.\n";
Sleep(7000);
cout << "Okay, tell me what to do, " << name << "." << endl;
getline(cin, song);
if (song.find(str2)){
cout << "Thank you! I, personally, love this song.\n";
cout << "I probably wouldn't listen to you if you asked me to turn it off.\n";
Sleep(20000);
}
else if (song.find(str3)){
cout << "It's not coming off, " << name <<"." << endl;
}
return 0;
}
return 0;
}
**EDIT:
I sort of fixed the issue.
I changed the above extract of code to this:
if (~song.find(str2))
{
cout << "Thank you! I, personally, love this song.\n";
cout << "I probably wouldn't listen to you if you asked me to turn it off.\n";
Sleep(20000);
}
else if (!~song.find(str2))
{
cout << "It's not coming off, " << name <<"." << endl;
Sleep(20000);
}
So it doesn't check for str3 anymore, but it does check if str2 is absent. This is progress, and fudges a solution, but it doesn't really give me a deeper understanding that I can bring forward with me so I would still appreciate answers :)
**
The line is incorrect :
if (input2 == "Yes" && "yes")
The && doesn't work that way. You have to perform the comparison with each value in the if statement. It should be:
if(input2 == "Yes" || input2 =="yes")
Likewise, the line
else if (input2 == "No" && "no")
should be:
if(input2 == "No" || input2 =="no")
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Okay I fixed the errors. Thank you guys. But now when I run it, I choose D in the menu but only "You chose to split the words & remove the duplicates in the paragraph" & "This is it:" prints out. It doesn't show anything after that ... Anyone know what it could be? Thank you in advance!!
This is how it should be:
When the 4th choice (“Split Words”) is selected, the words should be put into an array or a structure of your and each word should be displayed with a loop. After this duplicate removal should be performed and the program must determine the duplicate words and eliminate them. After this, the word list should be printed again
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <cctype>
#include <sstream>
#include <set>
using namespace std;
int main()
{
string s;
char selection;
string w;
string buf;
cout << "Enter a paragraph or a sentence : " ;
getline(cin, s);
int sizeOfString = s.length();
//cout << "The paragraph has " << sizeOfString << " characters. " << endl; ***Dummy call to see if size works.
//cout << "You entered " << s << endl; *** Dummy function !!
cout << "" << endl;
cout << " Menu " << endl;
cout <<" ------------------------" << endl;
cout << "" << endl;
cout << "A -- Convert paragraph to all caps " << endl;
cout << "B -- Convert paragraph to all lowercase " << endl;
cout << "C -- Delete whitespaces " << endl;
cout << "D -- Split words & remove duplicates " << endl;
cout << "E -- Search a certain word " << endl;
cout << "" << endl;
cout << "Please select one of the above: " ;
cin >> selection;
cout << "" << endl;
stringstream ss(s);
set<string> tokens;
switch (selection) //Switch statement
{
case 'a':
case 'A': cout << "You chose to convert the paragraph to all uppercase" << endl;
cout << "" << endl;
for(int i=0; s[i]!='\0'; i++)
{
s[i]=toupper(s[i]);
}
cout << "This is it: " << s << endl;
break;
case 'b':
case 'B': cout << "You chose to convert the paragragh to all lowercase" << endl;
cout << "" << endl;
for (int i=0; s[i] !='\0'; i++)
{
s[i]=tolower(s[i]);
}
cout << "This is it: " << s << endl;
break;
case 'c':
case 'C': cout << "You chose to delete the whitespaces in the paragraph" << endl;
cout << "" << endl;
for(int i=0; i<s.length(); i++)
if(s[i] == ' ') s.erase(i,1);
cout <<"This is it: " << s << endl;
break;
case 'd':
case 'D': cout << "You chose to split the words & remove the duplicates in the paragraph" << endl;
cout << "" << endl;
// Insert the string into a stream
// Create vector to hold our words
while (ss >> buf)
tokens.insert(buf);
cout << "This is it: " << endl;
for (set<string>::iterator it = tokens.begin(); it != tokens.end(); ++it)
{
cout << *it << " ";
}
cout << endl;
break;
case 'e':
case 'E': cout << "You chose to search for a certain word in the paragraph. " << endl;
cout << "" << endl;
cout << "Enter the word you want to search for: ";
cin >> w;
s.find(w);
if ( s.find( w ) != std::string::npos )
{
cout << w << " was found in the paragraph. " << endl;
}
else
{
cout << w << " was not found in the paragraph. " << endl;
}
}
return 0;
}
1)
set<s>::iterator
should be
set<string>::iterator
2) Add brackets around the case statements for the local variables.
case 'D':{
}
break;
case 'e':
case 'E':{
}
break;
You are creating stringstream with empty string, which, in turn leads to stream being empty. Consider creating stringstream object after you actually read the string. stringstream doesn't hold a reference to your string object, so any modification to a string the stringstream was based on, doesn't reflect those changes in the stream.
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 8 years ago.
Improve this question
I'm making a USD to MXN converter and I want to have it work both ways. The if statement works (tryed cout << "test"; and it worked) but it wont work when I replace it with the goto statement.
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int user;
int u, m;
cout << "US/MXN Converter" << endl;
cout << "1 US = 12.99 MXN (6/12/2014)" << endl;
cout << endl;
cout << "What Way to convert" << endl;
cout << "[1] US to MXN" << endl;
cout << "[2] MXN to US" << endl;
cout << "Selection: ";
cin >> user;
if (user == 1)
{
goto USTMXN;
}
else
{
goto MXNTUS;
}
USTMXN:
cout << "Enter the amount of US Dollars to Convert" << endl;
cout << "Amount: ";
cin >> u;
m = u * 12.99;
cout << endl;
cout << "MXN Pesos: " << m << endl;
goto END;
MXNTUS:
int mm, uu;
cout << "Enter the amount of Pesos to Convert" << endl;
cout << "Amount: ";
cin >> mm;
uu = mm / 12.99;
cout << endl;
cout << "US Dollars: " << m << endl;
goto END;
END:
system("PAUSE");
return EXIT_SUCCESS;
}
One of the most fundamental things we have to do as programmers is to learn to break problems into smaller problems. You are actually running into a whole series of problems.
I'm going to show you how to solve your problem. You may want to book mark this answer, because I'm pre-empting some problems you're going to run into a few steps down the line and preparing you - if you pay attention - to solve them on your own ;)
Let's start by stripping down your code.
Live demo here: http://ideone.com/aUCtmM
#include <iostream>
int main()
{
std::cout << "Enter a number: ";
int i;
std::cin >> i;
std::cout << "Enter a second number: ";
int j;
std::cin >> j;
std::cout << "i = '" << i << "', j = '" << j << "'\n";
}
What are we checking here? We're checking that we can ask the user two questions. That works fine.
Next is your use of goto, which I strongly recommend you do not use. It would be better to use a function. I'll demonstrate with your goto case here first:
#include <iostream>
int main()
{
int choice;
std::cout << "Enter choice 1 or 2: ";
std::cin >> choice;
if ( choice == 1 )
goto CHOSE1;
else if ( choice == 2 )
goto CHOSE2;
else {
std::cout << "It was a simple enough question!\n";
goto END;
}
CHOSE1:
std::cout << "Chose 1\n";
goto END;
CHOSE2:
std::cout << "Chose 2\n";
goto END;
END:
std::cout << "Here we are at end\n";
}
live demo: http://ideone.com/1ElcV8
So goto isn't the problem.
That leaves your use of variables. You've really mixed things up nastily by having a second set of variables (mm, uu). Not only do you not need to have these, you're doing something very naughty in that these variables only exist inside one scope and not the other. You can "get away" with this but it will come back to haunt you later on.
The difference in your two main streams of code is the variable names. The second conversion case looks like this:
MXNTUS:
int mm, uu;
cout << "Enter the amount of Pesos to Convert" << endl;
cout << "Amount: ";
cin >> mm;
uu = mm / 12.99;
cout << endl;
cout << "US Dollars: " << m << endl;
goto END;
The problem here is that you have - accidentally - used the variable "m" in your output. It's what we call uninitialized.
cout << "US Dollars: " << m << endl;
That m in the middle should be mm.
Your compiler should actually be warning you about this. If it's not, and you're just setting out learning, you should figure out how to increase the compiler warning level.
It would be better to make a function to do the conversions; you could make one function for each direction, but I've made a function that handles both cases:
#include <iostream>
static const double US_TO_MXN = 12.99;
static const char DATA_DATE[] = "6/12/2014";
void convert(const char* from, const char* to, double exchange)
{
std::cout << "Enter the number of " << from << " to convert to " << to << ".\n"
"Amount: ";
int original;
std::cin >> original;
std::cout << to << ": " << (original * exchange) << '\n';
}
int main() // this is valid since C++2003
{
std::cout << "US/MXN Converter\n"
"1 US = " << US_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"\n";
int choice = 0;
// Here's a better demonstration of goto
GET_CHOICE:
std::cout << "Which conversion do you want to perform?\n"
"[1] US to MXN\n"
"[2] MXN to US\n"
"Selection: ";
std::cin >> choice;
if (choice == 1)
convert("US Dollars", "Pesos", US_TO_MXN);
else if (choice == 2)
convert("Pesos", "US Dollars", 1 / US_TO_MXN);
else {
std::cerr << "Invalid choice. Please try again.\n";
goto GET_CHOICE;
}
// this also serves to demonstrate that goto is bad because
// it's not obvious from the above that you have a loop.
}
ideone live demo: http://ideone.com/qwpRtQ
With this, we could go on to clean things up a whole bunch and extend it:
#include <iostream>
using std::cin;
using std::cout;
static const double USD_TO_MXN = 12.99;
static const double GBP_TO_MXN = 22.03;
static const char DATA_DATE[] = "6/12/2014";
void convert(const char* from, const char* to, double exchange)
{
cout << "Enter the number of " << from << " to convert to " << to << ".\n"
"Amount: ";
int original;
cin >> original;
cout << '\n' << original << ' ' << from << " gives " << int(original * exchange) << ' ' << to << ".\n";
}
int main() // this is valid since C++2003
{
cout << "Foreign Currency Converter\n"
"1 USD = " << USD_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"1 GBP = " << GBP_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"\n";
for ( ; ; ) { // continuous loop
cout << "Which conversion do you want to perform?\n"
"[1] USD to MXN\n"
"[2] MXN to USD\n"
"[3] GBP to MXN\n"
"[4] MXN to GBP\n"
"[0] Quit\n"
"Selection: ";
int choice = -1;
cin >> choice;
cout << '\n';
switch (choice) {
case 0:
return 0; // return from main
case 1:
convert("US Dollars", "Pesos", USD_TO_MXN);
break;
case 2:
convert("Pesos", "US Dollars", 1 / USD_TO_MXN);
break;
case 3:
convert("British Pounds", "Pesos", GBP_TO_MXN);
break;
case 4:
convert("Pesos", "British Pounds", 1 / GBP_TO_MXN);
break;
default:
cout << "Invalid selection. Try again.\n";
}
}
}
http://ideone.com/iCXrpU
There is a lot more room for improvement with this, but I hope it helps you on your way.
---- EDIT ----
A late tip: It appears you're using visual studio, based on the system("PAUSE"). Instead of having to add to your code, just use Debug -> Start Without Debugging or press Ctrl-F5. It'll do the pause for you automatically :)
---- EDIT 2 ----
Some "how did you do that" points.
cout << '\n' << original << ' ' << from << " gives " << int(original * exchange) << ' ' << to << ".\n";
I very carefully didn't do the using namespace std;, when you start using more C++ that directive will become the bane of your existence. It's best not to get used to it, and only let yourself start using it later on when you're a lot more comfortable with C++ programming and more importantly debugging odd compile errors.
But by adding using std::cout and using std::cin I saved myself a lot of typing without creating a minefield of function/variable names that I have to avoid.,
What does the line do then:
cout << '\n' << original << ' ' << from << " gives " << int(original * exchange) << ' ' << to << ".\n";
The '\n' is a single character, a carriage return. It's more efficient to do this than std::endl because std::endl has to go poke the output system and force a write; it's not just the end-of-line character, it actually terminates the line, if you will.
int(original * exchange)
This is a C++ feature that confuses C programmers. I'm actually creating a "temporary" integer with the result of original * exchange as parameters.
int i = 0;
int i(0);
both are equivalent, and some programmers suggest it is better to get into the habit of using the second mechanism so that you understand what happens when you later run into something called the "most vexing parse" :)
convert("Pesos", "British Pounds", 1 / GBP_TO_MXN)
The 1 / x "invert"s the value.
cout << "Foreign Currency Converter\n"
"1 USD = " << USD_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"1 GBP = " << GBP_TO_MXN << " MXN (" << DATA_DATE << ")\n"
"\n";
This is likely to be confusing. I'm mixing metaphors with this and I'm a little ashamed of it, but it reads nicely. Again, employ the concept of breaking problems up into smaller problems.
cout << "Hello " "world" << '\n';
(note: "\n" and '\n' are different: "\n" is actually a string whereas '\n' is literally just the carriage return character)
This would print
Hello world
When C++ sees two string literals separated by whitespace (or comments) like this, it concatenates them, so it actually passes "Hello world" to cout.
So you could rewrite this chunk of code as
cout << "Foreign Currency Converter\n1 USD = ";
cout << USD_TO_MXN;
cout << " MXN (";
cout << DATA_DATE;
cout << ")\n1 GBP = ";
cout << GBP_TO_MXN;
cout << " MXN (";
cout << DATA_DATE;
cout << ")\n\n";
The << is what we call "semantic sugar". When you write
cout << i;
the compiler is translating this into
cout.operator<<(i);
This odd-looking function call returns cout. So when you write
cout << i << j;
it's actually translating it to
(cout.operator<<(i)).operator<<(j);
the expression in parenthesis (cout.operator<<(i)) returns cout, so it becomes
cout.operator<<(i); // get cout back to use on next line
cout.operator<<(j);
Main's fingerprint
int main()
int main(int argc, const char* argv[])
Both are legal. The first is perfectly acceptable C or C++. The second is only useful when you plan to capture "command line arguments".
Lastly, in main
return 0;
Remember that main is specified as returning int. The C and C++ standards make a special case for main that say its the only function where it's not an error not to return anything, in which case the program's "exit code" could be anything.
Usually its best to return something. In C and C++ "0" is considered "false" while anything else (anything that is not-zero) is "true". So C and C++ programs have a convention of returning an error code of 0 (false, no error) to indicate the program was successful or exited without problems, or anything else to indicate (e.g. 1, 2 ... 255) as an error.
Using a "return" from main will end the program.
Try to change youre code for sth like this. Using goto label is not recommended.
Main idea of switch statement :
int option;
cin >> option
switch(option)
{
case 1: // executed if option == 1
{
... code to be executed ...
break;
}
case 99: //executed id option == 99
{
... code to be executed
break;
}
default: // if non of above value was passed to option
{
// ...code...
break;
}
}
Its only example.
int main(int argc, char *argv[])
{
int user;
int u, m;
cout << "US/MXN Converter" << endl;
cout << "1 US = 12.99 MXN (6/12/2014)" << endl;
cout << endl;
cout << "What Way to convert" << endl;
cout << "[1] US to MXN" << endl;
cout << "[2] MXN to US" << endl;
cout << "Selection: ";
cin >> user;
switch(user )
{
case 1 :
{
//USTMXN:
cout << "Enter the amount of US Dollars to Convert" << endl;
cout << "Amount: ";
cin >> u;
m = u * 12.99;
cout << endl;
cout << "MXN Pesos: " << m << endl;
break;
}
}
default :
{
//MXNTUS:
int mm, uu;
cout << "Enter the amount of Pesos to Convert" << endl;
cout << "Amount: ";
cin >> mm;
uu = mm / 12.99;
cout << endl;
cout << "US Dollars: " << m << endl;
break;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
I am doing a quiz and testing the user. If the user is wrong he is allowed a second chance or skip, if he chooses 2nd chance and is wrong again, the game is over. How do I break out of this loop to end the game? I tried a do while loop,
do { stuff} while (wrong<2) while counting ++wrong;
every time he's wrong, but didnt work.
I have labeled the ++wrong with // statements below
void player_try (string questions[][5], char answers[])
{
char user_guess;
int m = 0;
srand(time(NULL));
int x;
int choice;
int wrong =0;
for (m=0; m<7; m++)
{
do
{
x = (rand() % 7);
cout << user_name << ": Here is question number " << m+1 << endl;
cout << m+1 << ". " << questions[x][0]<< endl;
cout << "A. " << questions[x][1]<< endl;
cout << "B. " << questions[x][2]<< endl;
cout << "C. " << questions[x][3]<< endl;
cout << "D. " << questions[x][4]<< endl;
cin >> user_guess;
user_guess = toupper(user_guess);
while (!(user_guess >= 'A' && user_guess <= 'D'))
{
cout << "Please choose a valid answer.";
cin>> user_guess;
}
if (user_guess != answers[x])
{
cout <<"Wrong!" <<endl;
++wrong; // THIS IS WHERE I COUNT WRONG ONCE
cout << "Skip this question or take a chance at greatness?" << endl;
cout << "Press 1 to skip, press 2 to take a chance at greatness" << endl;
cin >> choice;
if (choice == '1')
{
cout << "we shall skip this question." << endl;
}
else
{
cout << "I applaud your bravery." << endl;
cout << user_name << ": Here is question number " << m+1 << endl;
cout << m+1 << ". " << questions[x][0]<< endl;
cout << "A. " << questions[x][1]<< endl;
cout << "B. " << questions[x][2]<< endl;
cout << "C. " << questions[x][3]<< endl;
cout << "D. " << questions[x][4]<< endl;
cin >> user_guess;
user_guess = toupper(user_guess);
while (!(user_guess >= 'A' && user_guess <= 'D'))
{
cout << "Please choose a valid answer.";
cin>> user_guess;
}
}
if (toupper(user_guess) != answers[x])
{
cout <<"Wrong!" <<endl;
++wrong;; // THIS IS WHERE I CANT WRONG TWICE
}
else
{
cout << "correct!" << endl;
}
}
else
{
cout << "correct!" << endl;
}
}
while(wrong < 2);
}
}
Change your function return type to an integer. That simply means changing "void" to "int."
Then, inside the function place a return 0; at the point you want your function to terminate. Be sure you include another return 1; for the case that the user wins too.
This is how the main() function works. Consider:
int main()
{
string tester = "some string";
if(tester == "some string")
return 1;
cout << "Hey!"
return 0;
}
In the above case, main() terminates at the "return 1;" because the if statement was TRUE. Note that "Hey!" is never printed. It'll work the same way for your function.
As a plus, you can use that return value to let OTHER functions (such as main()) know if the function terminated because the user won (it returned 1), or lost (it returned 0).
Yes, a break statement is also a valid way to terminate the loop, but I submit that this method is the safer, cleaner way to go about it. In general, we like to know whether a function or program was successful or not.
You can use a break; statement if the person has gotten the answer wrong twice.
As per comments. You can shed the do while loop in favour of one for loop. Just put a break at the bottom if the wrong guesses are 2
There are several great suggestions for refactoring the code to remove the duplication of effort here, but to get the program functioning immediately, you've got to break out of the for loop surrounding the do { } while(wrong < 2) loop.
A simple way to do this is to modify the for loop to test the wrong variable also. The added benefit is, if I'm reading everything correctly, you'll no longer need the do{ } while(); loop.
for (m=0; m<7 && wrong < 2; m++)