EXC_BAD_ACCESS error with arrays in C++ - c++

sorry if this is a stupid question but I'm trying to write a program that compares 7 numbers that a user inputs to 7 numbers that the computer generates(a kind of lottery simulator). However, when i try to input the 7 numbers that the user inputs the program crashes after the second input. Please help, and thanks in advance!
This is the beginning of my main:
#include <iostream>
#include <iomanip>
#include "Implementation.hpp"
using namespace std;
int main()
{
string name;
cout << "What is your name?\n";
getline(cin, name);
while(1 != 0) //I know this will never be true, I'm just doing it
//because the return statement will
{ //end the program anyways if the user inputs 2
int *userNums = new int[7];
int *winningNums = new int[7];
int cont;
int matches;
cout << "LITTLETON CITY LOTTO MODEL\n";
cout << "--------------------------\n";
cout << "1) Play Lotto\n";
cout << "2) Quit Program\n";
cin >> cont;
if(cont == 2)
return 0;
getLottoPicks(&userNums);
And this is the getLottoPicks function:
void getLottoPicks(int *picks[])
{
int numsAdded = 0, choice;
while(numsAdded <= 7)
{
cout << "Please input a valid number as your lotto decision.\n";
cin >> choice;
if(noDuplicates(*picks, choice) == false)
continue;
*picks[numsAdded] = choice;
numsAdded++;
}
}
I'm fairly certain that it is a problem with the pointers that i'm trying to use, but without them I can't actually change the arrays I don't think, and I couldn't get the function to return an array.

If you're using C++, then you're probably better using a std::vector<int>, and passing in the reference to the vector in getLottoPicks.
However, your code should only be passing the int * to the getLottoPicks, and should process < 7 items - it's the classic off-by one.
call to getLottoPicks:
getLottoPicks(userNums);
and the new getLottoPicks code:
void getLottoPicks(int *picks)
{
int numsAdded = 0, choice;
while(numsAdded < 7)
{
cout << "Please input a valid number as your lotto decision.\n";
cin >> choice;
if(noDuplicates(picks, choice) == false)
continue;
picks[numsAdded] = choice;
numsAdded++;
}
}

Related

Whats a good way to get the program to end based on user input?

I did my "Hello World", I'm just getting started on my programming adventure with C++. Here is the first thing I've written, what are some ways to get it to end with user input? I'd like a yes or no option that would terminate the program. Also any feedback is welcome, thank you
#include <iostream>
using namespace std;
void Welcome();
void calculateNum();
void tryAgain();
int main() {
Welcome();
while (true) {
calculateNum();
tryAgain();
}
system("pause");
}
void calculateNum() {
float userNumber;
cin >> userNumber;
for (int i = 100; i >= 1; i--) {
float cNumber = i* userNumber;
cout << i << " >>>>> " << cNumber << endl;
}
}
void Welcome() {
cout << "Welcome \n Enter a number to see the first 100 multiples \n";
}
void tryAgain() {
cout << "Try again? Enter another number... ";
}
Here is one option:
Switch to do ... while loop, with the condition at the end.
Make your tryAgain() function return a boolean and put it in the while condition.
In tryAgain function read input from the user, and compare it to expected answers.
First, lets add a new header for string, it will make some things easier:
#include <string>
Second, lets rebuild the loop:
do {
calculateNum();
} while (tryAgain());
And finally, lets modify the function:
bool tryAgain() {
string answer;
cout << "Try again? (yes / no)\n";
cin >> answer;
if (answer == "yes") return true;
return false;
}
Now, there is a slightly shorter way to write that return, but it might be confusing for new learners:
return answer == "yes";
You don't need the if because == is an operator that returns bool type value.
You can change your calculateNum() in the following way:
Change the return value of your calculateNum() function into bool to indicate whether the program shall continue or stop
read the input into a std::string
check if the string is equal to your exit string like 'q' for quit
3.a in that case, your function returns false to indicate the caller that the program shall stop
3.b otherwise, create a stringstream with your string and read the content of the stream into your float variable and continue as you do like now
In your loop in your main function you break if calculateNum() returned false
Here is a simple solution:
#include <iostream>
// Here are two new Includes!
#include <sstream>
#include <string>
using namespace std;
void Welcome();
// Change return value of calculateNum()
bool calculateNum();
void tryAgain();
int main()
{
Welcome();
while (true)
{
if (!calculateNum())
break;
tryAgain();
}
system("pause");
}
bool calculateNum()
{
//Read input into string
string userInput;
cin >> userInput;
//Check for quit - string - here just simple q
if (userInput == "q")
return false;
//otherwise use a std::stringstream to read the string into a float as done before from cin.
float userNumber;
stringstream ss(userInput);
ss >> userNumber;
//and proces your numbers as before
for (int i = 100; i >= 1; i--)
{
float cNumber = i * userNumber;
cout << i << " >>>>> " << cNumber << endl;
}
return true;
}
void Welcome()
{
cout << "Welcome \n Enter a number to see the first 100 multiples \n";
}
void tryAgain()
{
cout << "Try again? Enter another number... ";
}
Having your users input in a string you can even do further checks like checking if the user entered a valid number, interpret localized numbers like . and , for decimal delimitters depending on your system settings and so on.

Undefined behaviour when entering `char` for integer variable with `std::cin`

I have this while loop, just to check if the entered number is 2. If the user entered by accident a letter instead of a number the loop goes to infinity even though I've added isdigit, but didn't fix the loop from going crazy if the input is a character. This is code:
int num1;
bool cond {false};
while(!cond){
cout<<"enter 2:";
cin>>num1;
if (!isdigit(num1)){
cout<<"not a digit:";
cin>>num1;
}
//
if(num1 == 2)
cond = true;
}
I would suggest trying something a little more straightforward instead of your current code:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int num1;
cout << "Please enter the number 2:";
cin >> num1;
while (num1 != 2)
{
cin.clear(); //Clears the error flag on cin.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "You did not enter the number 2, Please try again:";
cin >> num1;
}
return 0;
}
Now, cin.ignore(numeric_limits<streamsize>::max(), '\n'); is when it ignores up until '\n' or EOF \n is the delimiter meaning that, that is the character at which cin will stop ignoring.
Furthermore, numeric_limits<streamsize>::max() is basically saying there is no limit to the number of characters to ignore.
You need to use the header file #include<limits> to use this.
I recommend separating the reading of input data from converting it to a number. A good method for this is to use stringstream. Here's a working example:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int num1;
string input;
bool cond{ false };
cout << "enter 2:";
while (!cond) {
getline(cin, input);
stringstream ss(input);
ss >> num1;
if( ss.fail() ){
cout << "not a digit:";
continue;
}
//
if (num1 == 2)
cond = true;
else
cout << "enter 2:";
}
return 0;
}
int num1;
bool cond {false};
do{
cout<<"enter 2:";
cin>>num1;
if (cin.good()) {
cond = true;
}else {
cin.clear();
cin.ignore();
cout << "Invalid, please enter 2." << endl;
}
}while(!cond);
While false, execute statements. Also, if you want the user to re-enter a number, cin must be flushed.
Try declaring the variable num1 as char because isdigit(ch) works for char and not for int.
I hope this solves your problem
Why does the loop iterate infinitely?
Let's take this example
int a;
std::cin >> a;
std::cout << "Entered: " << a;
Now let's test it with different inputs
with int
5
Entered: 5
10
Entered: 10
Yes just as we would expect, but what happens when you enter a char?
with char
r
Entered: 0
f
Entered: 0
Why does this happen?
When you declare the variable int, and then do std::cin >> , you are telling the input method that the user will enter an integer, but when it doesn't get what it expected, it will fail. C++ will not implicitly convert the value of char into int. Hence, you get strange results.
How to solve this?
As I have mentioned earlier, it fails. When this fails you can catch it this way
if (!(std::cin >> a))
{
std::cout << "Invalid input ! \n";
}
We're saying, if the input fails, show the message.
let's test this new code.
int a;
if (!(std::cin >> a))
{
std::cout << "Invalid input !\n";
}
else
{
std::cout << "Entered: " << a;
}
5
Entered: 5
r
Invalid input !
How to print char value of the int?
If you want to just print the ASCII value of the entered number, you need to cast the value into char.
You can do
int num = 48;
char character_value = num;
Here C++ will implicitly convert char into int.
But if you need a safer type of conversion, prefer using static_cast<>.
The syntax looks like this
int a = 5;
char character_value = static_cast<char>(a);
Static cast in C++
Type casting in C++
Dealing with invalid input in C++

How do I use recursion to loop my code (when user enters invalid input, it prompts them again)?

So I wrote this code in C++ format and I am trying to loop the code as to when the user enters an invalid input when prompted to enter a number between 1 and 10 it doesn't just terminate if invalid input, but asks the user to enter a valid input until correct a valid input is entered. New to c++ so I'd appreciate the help
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std;
//constants go here
const int MIN = 1;
const int MAX = 10;
const char YES = 'Y';
const char NO = 'N';
//Booleans go here
char wantToPlay();
bool getIntValue(int &userValue);
bool play(int userValue);
//Main routine
int main(){
printf("Welcome, this program will guess a number between 1 and 10");
printf(", if the program guesses the number correctly you'll get VICTORY ROYALE");
printf(", if you don't get it right you'll get BETTER LUCK NEXT TIME, Good luck :)\n");
char playOrNot = wantToPlay();
//If user value is TRUE, program outputs "Victory Royale" and terminates
//If user value is FALSE, program outputs "Better luck next time" and terminates
//If user value is NOT VALID, program outputs "Not a good number" and prompts user again
//If user enters "N" when prompted to answer Y or N
int input = -1;
switch (playOrNot){
case YES:
if(getIntValue(input)){
srand (time(NULL));
if(play(input)){
cout << "Victory Royale!"<<endl;
}else{
cout<<"Better Luck Next Time!"<<endl;
}
}else{
cout<<"not a good number\n";
}
break;
case NO:
cout << "sorry you hate my game\n";
break;
default:
cout << "that was not valid\n";
//If user enters value that is completely not valid
}
return 0;
}
char wantToPlay(){
//Prompt user to enter Y for yes and N for no
char answer = NO;
cout << "Do you Want to Play? 'y'for" << " yes, 'n' for no" << endl;
cin >> answer;
answer = toupper(answer);
return answer;
}
bool getIntValue(int &userValue){
//Prompt user to enter a number between the Min(1) and Max(10)
bool valid = false;
cout <<"Enter a number between " << MIN << " and " << MAX <<endl;
cin>>userValue;
if(userValue >= MIN && userValue <= MAX){
valid = true;
}
return valid;
}
bool play(int userValue){
//Random tool to give a random between 1 and 10
bool match = false;
int random = (rand()%10)+1;
if(userValue==random){
match=true;
}
return match;
}
#include<iostream>
using namespace std;
int main()
{
char s;
cout<<"Enter valid number between 1 to 10"<<endl;
cin>>s;
while(!((s>='1') && (s<='10')))
{
cout<<"The number you have entered is not in range 1 - 10"<<endl;
cout<<"Enter an valid number I.e. between 1 to 10"<<endl;
cin>>s;
}
cout<<"You have successfully entered an valid number"<<endl;
return;
}

Getting identifier choice is undefined

I'm working on a calculator console app. I'm a beginner in C++ I want the program to ask a question after I'm done printing the previous result. I get the following error though and I have no idea how to fix it.
identifier "choice" is undefined
Here is my source code:
#include "stdafx.h"
#include <iostream>
int getUserInput() {
std::cout << "Please enter an integer: ";
int value;
std::cin >> value;
return value;
}
int getConversionFormula() {
std::cout << "What do you want to convert? (1 for Meters to feet, 2 for kilometers to miles, 3 for kilagrams to pounds.): ";
int op;
std::cin >> op;
//user might select an invalid operation that isnt there
//Implement a way to avoid this.
return op;
}
int getUserInput2() {
std::cout << "Do you want to convert anything else? (hit 1 for yes, hit 2 for no): ";
int choice; //for the user if they hit yes or no to the question above.
std::cin >> choice;
return choice;
}
int getUserChoice(int choice) {
//If user selects 1 show the converstion formula screen
if (choice == 1)
getConversionFormula();
if (choice == 2)
std::exit;
return -1;
}
int calculateResult(int x, int op) {
//we will use == to compare two variables to see if they are true or not
if (op == 1)
return x * 3.280839895; //meters to feet
if (op == 2)
return x / 1.609344; //km to miles
if (op == 3)
return x * 2.2046; //kg to pounds
return -1; //If the user entered an invalid operation
}
void printResult(int result) {
std::cout << "Your result is: " << result << std::endl;
}
int main()
{
int input1 = getUserInput(); //Gets the users input
int op = getConversionFormula();
int result = calculateResult(input1, op);
printResult(result);
int input2 = getUserInput2(); //Asks the user if they want to convert anything else
int input3 = getUserChoice(input2, choice);
std::cin.clear(); // reset any error flags
std::cin.ignore(32767, '\n'); // ignore any characters in the input buffer until we find an enter character
std::cin.get(); // get one more char from the user
}
Can someone please tell me how I can fix it? I get the error in the main function just to let everyone know.
choice is not declared in main, it's only in getUserInput2, which it returns. getUserChoice doesn't even take two arguments, so just do:
getUserChoice(input2);
You could start chaining your function calls a bit, e.g.: getUserChoice(getUserInput2()); and thus eliminate a few local variables.

C++ input not being read

I just started with c++ (coming from java) and I'm trying to do some basic exercises. The idea is to ask for any input other than 5, if the user inputs 5, display a message, and if the user inputs anything other than 5 ten times, display another message. Here's the code:
void notFive () {
int count = 0;
while (count < 10) {
int input = 0;
cout << "Enter any number other than 5." << endl;
cin >> input;
if (input == 5)
break;
count++;
}
if (count == 10)
cout<<"You are more patient than I am, you win.";
else
cout << "You weren't supposed to enter 5!";
}
}
My problem is that all this code does is print out "Enter any number other than 5." 10 times, then say "You are more patient that I am, you win." any ideas what is wrong?
if you guys want all my code (to make sure I'm not just being an idiot) here it is:
#include <iostream>
#include <stdio.h>
using namespace std;
class Hello {
public:
void notFive () {
int count = 0;
while (count < 10) {
int input = 0;
cout << "Enter any number other than 5." << endl;
if ( ! (cin >> input) ) {
cout << "std::cin is in a bad state! Aborting!" << endl;
return;
}
if (input == 5)
break;
count++;
}
if (count == 10)
cout<<"You are more patient than I am, you win.";
else
cout << "You weren't supposed to enter 5!";
}
}hello;
int main() {
Hello h;
h.notFive();
return 0;
}
Your code works perfectly for me (in Visual Studio 2012) when I change notFive to main. Your problem must lie outside this code (possibly because cin is in a broken state, as others have suggested).
Change this line:
cin >> input
To this:
if ( ! (cin >> input) ) {
cout << "std::cin is in a bad state! Aborting!" << endl;
return;
}
The behavior you describe is what would happen if Something Bad happened to cin before this code was run.
Edit:
Add this same code to earlier uses of cin to find out where it's entering a bad state.
An example of this happening would be if the code tried to read an int, and the user typed a letter of the alphabet.
You can also call cin.clear(); to restore the working state of cin.
Here are my comments:
fflush(stdin) is not valid. The stdin cannot be flushed. Also,
this may not be the same input as cin.
You need to check for cin.fail after cin >> input. If I enter a
letter, your input statement will fail.