Function automatically looping? - c++

Ok, so this function is supposed to take results from a user and then give them an option to input more results or return to the main menu main() when they're done.
Everything works fine. the only problem is at the last scanf statement before the switch.
Instead of waiting for the users input in userChoice, its automatically starting the function over again. Its only supposed to do that if userChoice is 'a' or 'A' but it just completely ignores the scanf statement and the switch as well, it seems. What am i doing wrong? Scroll down to see the line im referring to.
void inputResults(int gameNumber, int i, int j)
{
int Results[ROWS][COLS];
char userChoice = ' ';
if (j >= COLS)
{
j = 0;
i = i + 1;
}
if (gameNumber > ROWS)
{
printf("\nJk, Max number of games reached\n");
main();
}
gameNumber = gameNumber + 1;
printf("\nHow many points did the home team score in game %d?\n", gameNumber);
scanf_s("%d", &Results[i][j]);
j = j + 1;
printf("\nHow many points did the opponents score in game %d?\n", gameNumber);
scanf_s("%d", &Results[i][j]);
printf("\nHome: %d Opponents: %d\n", Results[i][j-1], Results[i][j]);
printf("\nA) Enter results for game %d\nB) Main menu \n", (gameNumber + 1));
*************************PROBLEM***********************************
scanf_s("%c", &userChoice); /*it ignores THIS it just loops the
function after it prints the above*/
switch (userChoice) //it doesnt even get to this.
{
case 'A':
inputResults(gameNumber, i, j);
case 'a':
inputResults(gameNumber, i, j);
case 'b':
main();
case 'B':
main();
default:
printf("\nThats still not a valid choice dude\n");
}
}
the values passed into gameNumber, i, and j are all all 0 if you're wondering. They were passed from the main function

When you read a single character with scanf_s like
char ch;
scanf_s("%c", &ch, 1);
and enter for eg. the letter 'A' and press enter, the 'A' ends up in ch but the '\n' from you pressing enter remains in stdin. On the next call to scanf_s() this '\n' is read and stored in ch without giving you the chance of making any input.
Use
scanf_s("%c[^\n]", &ch, 1);
instead which will read and discard all extra characters still in stdin up to the next newline character.

Related

Why is it that the second code gives the desired result while the first doesn't?

When I use functions I get the desired result which is:-
1)The command window asks me to give input every time so I can input 'q' as many times as I want and can even enter 'e' to exit
2) Every time I press 'q' score decreases by 1
whereas in the code without functions the following happens:-
1) I press 'q' and the score keeps decreasing indefinitely
2) Cannot enter another input like 'e' once entered 'q'
#include<iostream>
using namespace std;
int main()
{
char h;
cin>>h;
int n = 10;
do{
system("cls");
cout<<"score is"<<n;
if(h == 'q')
{
n=n-1;
}
}while(h != 'e');
return 0;
}
CODE 2 with FUNCTION:-
#include<iostream>
using namespace std;
char input;
int n = 10;
bool over = false;
void ip()
{
system("cls");
cout<<"score is"<<n;
cin>>input;
switch(input)
{
case 'q':
n--;
break;
case 'e':
over = true;
break;
}
}
int main()
{
do{
ip();
}while(!over);
return 0;
}
Please explain to me how is the program looping through the function and how is it looping through the 'IF' statement alone. Because the condition statement is there in the function also (switch statement) so why isn't the function decreasing the score or the value of 'n' indefinitely??
I figured out my mistake in the first code (without functions) the cin>> statement should be inside do-while loop so that after every loop input is asked.

While loop and if/else statement not working correctly

The issue I am running into is that when I run the code, it adds correctly but when it comes time to run the if or else statement, nothing happens. It always just ends.
#include <iostream>
using namespace std;
int main()
{
int firstNumber;
int secondNumber;
int sum;
char restart = 1;
while (restart == 1)
{
cout<<"Welcome to My Calculator!\n\n";
cout<<"What is the first number you would like to add?\n\n";
cin>>firstNumber;
cout<<"What is the second number you would like to add?\n\n";
cin>>secondNumber;
cout<<"Wonderful! Getting together your result now....\n\n";
sum = firstNumber + secondNumber;
cout<< sum<<endl;
cout<<"If you have another question, just enter 1, if not press 2!\n\n";
cin>>restart;
if (restart == 1)
{
cout<<"No problem!\n\n";
}
else
{
cout<<"Goodbye!";
}
}
return 0;
}
char restart = 1;
if (restart == 1)
needs to be
char restart = '1';
if(restart == '1')
There is a difference between 1 and '1'. When you want to compare chars you use the '' marks.
Also, you should also always initialize your ints
This is because C++ doesn't automatically set it to zero for you. So, you should initialize it yourself:
int sum = 0;
An uninitialized variable has a random number such as 654654,-5454, etc. (If it doesn't invoke undefined behavior when reading it)

The program crashes after executing while loop

The code shuts down after executing the while loop and does not execute the last 2 printf statements. I don't know whats wrong.. after the loop goes around for the chosen times the program just closes.
#include <stdio.h>
int main()
{
int numberofq;
int questionansc;
int questionansic;
int counter;
int answer;
numberofq = 0;
questionansc = 0;
questionansic = 0;
counter = 0;
answer = 0;
while(numberofq <1 || numberofq >5)
{
printf("Hello enter the amount of questions you want between 1 and 5 \n");
scanf("%d", &numberofq);
} // End While
//Program runs until the counter is less than users wanted question number.
while (counter < numberofq)
{
//Question 1
printf("Question 1. what is 2+2? \n");
scanf("%d" , &answer);
//if users answer is equal to 4.
if (answer == 4)
{
printf("You entered %d, you are correct\n", answer);
questionansc = questionansc +1;
} //End If
//If the answer is not equal to 4.
else
{
printf("You entered %d, you are wrong correct answer is 4 \n", answer);
questionansic = questionansic +1;
} // End Else
counter = counter +1;
//End Question 1.
} //End While
printf("You got %d questions correct \n" , questionansc);
printf("You got %d questions wrong" , questionansic);
flushall();
return 0;
} // End Main`
It actually prints them and then exits, but it exits so quickly you don't have a chance to see this.
You can pause execution using system("pause") on Windows, but that's considered bad practice. You could use getch() or something, but you could also simply invoke the program from an existing CMD/Terminal and in this way the output will stay there after the program is done.

c++ Roman Additive Form Conversion

I'm working in a program that converts from Roman to Decimal. I have to validate 2 things: One that the characters entered are M or D or C or L or X or V or I, in other words valid for processing.
Number two, I have to make sure that bigger characters value go first and if not to print and error message and have the user to try again (this is the part where I am stuck)
For instance, If I wanted to input 9 and I input IX it should display an error message because is not in Additive form. It should be VIIII. How can I code this so it compares characters to know whether bigger letter values are first and so on?
I keep getting incorrect validation.
Is there a way to assign a value to the letters in the string? I'm thinking in comparing them as int values which I know how to and from there validate input format.
void RomanNum::setRomanNumber() //get input and calculate decimal equivalent
{
//I 1, V 5, X 10, L 50, C 100, D 500, M 1000
int value = 0;
string input;
char current, next;
enum validationData { M, D, C, L, X, V, I };
bool validationCharacters = true;
//bool validationAdditiveForm = true;
getline(cin, input, '\n');
for (int i = 0; i < input.length(); i++) //calculate each Roman letter at a time
{
current = input[i];
next = current + 1;
if (current >= validationData(next))
{
switch (input[i])
{
case 'M':
value += 1000;
break;
case 'D':
value += 500;
break;
case 'C':
value += 100;
break;
case 'L':
value += 50;
break;
case 'X':
value += 10;
break;
case 'V':
value += 5;
break;
case 'I':
value += 1;
break;
default:
validationCharacters = false;
break;
}
}
else
{
cout << "\nInvalid order. Bigger values go first\n";
}
}
}
I would recommend a std::map<char, int> to hold the mapping between letetrs and values.
With the map, you can then convert the input string (a sequence of characters) to a sequence of values (std::vector<int>). From there on, it's just a single check to see if the vector is sorted, and a single function call to add up all values. (I'll leave finding the right function as homework)

Reading a list of characters and storing in an array

I am having issues with the following code and I cant figure out why out of loop is not being printed. With this code I want the program to ignore any spaces inputted by the user and after a space is inputted the number previously entered is stored in an array location. Like this I want 6 and 78 to be stored in 2 array locations not store them individually as 6 7 8.
This is my code:
while ((in=getchar()) != '0')
{
if (in == ' ')
{
printf("space\n ");
continue;
}
else
{
printf("assigning\n ");
input[i]=in;
}
i++;
}
printf("Out of Loop");
My output when inputting 5 6 78 is:
assigning
space
assigning
space
assigning
assigning
assigning
With this output I doubt whether 78 is being stored in one memory location.
I would really appreciate your help,Thankyou
C++:
std::vector<int> v;
std::string s;
int i;
std::getline( std::cin, s); // read full line with whitespaces
std::istringstream iss( s); // prepare to process the line
while( iss >> i) v.push_back( i); // read into i and push into vector if
// operator>> was successful
C:
int array[ 10];
int i = 0, retval;
while( i < 10 && ( retval = scanf( "%d", &array[ i++])) == 1) ;
if( i == 10) {
// array full
}
if( retval == 0) {
// read value not an integer. matching failure
}
if( retval == EOF) {
// end of file reached or a read error occurred
}
You are deciding character by character. Thus, you will only store single digits or ignore those digits.
You could store the whole numbers like this (extending your code):
bool currentNumberStarted = false;
int currentNumber = 0;
int idx = 0;
while ((in=getchar()) != '0')// you probably want '\0' instead of '0'
{
if (in == ' ')
{
if (currentNumberStarted)
{
input[idx]=currentNumber;
idx++;
currentNumberStarted = false;
}
printf("space\n ");
continue;
}
else
{
printf("assigning\n ");
currentNumberStarted = true;
currentNumber *= 10;
currentNumber += in;
}
}
printf("Out of Loop");
First of all I highly doubt that your while loop will ever end, even if you made that to '\0' ,Because you are using char variable to store input. Not strings, Only strings uses '\0' at the end,How can we enter '\0' from keyboard..???. even if you want to keep it as '0',you would alwasy have to enter 0 as last number to end the loop(which i think you dont want to.)
So the Solution is this:-
After Entering Numbers You will Hit ENTER key, which would generate a newline character '\n' so you have to check for new line character('\n'), And as you are using getchar() function, it will returns EOF (-1) at the end of input, so its important to check for it too.So you have to check for both '\n' and EOF at once in while loop.And at last you should also check for array index number(it should be less than 1) in which you are storing numbers.
I made some effort to make you understand the program in comments.
int main()
{
int i=0;
int input[10]={0}; //here only 10 integers can be entered(hence i should be i<10)
int in; //To store input character
int num=0; //To store number which is converted from character.
int new=1; //To check if new number is started 0=false 1=True.
int count=0;//This is just to know how many numbers entered,also used to print numbers at end.
while ((in=getchar()) != '\n' && (in!=EOF) && i<10)//should check for both '\n' and EOF and array index also
{
if (in == ' ')
{
printf("space\n ");
if(new==0) //if new Number is not started yet.
{
new=1; //Start of a New number.(a number entered after space)
i++; //As new number is started it should be stored in new array index.
}
continue; //if space is entered just go to begining
}
else
{
printf("assigning\n ");
num=in-48; //converts a character to number (ex:- converts '3' to 3)
input[i]=(input[i]*10)+num; //storing the number..This is important do a paper work to understand this step.
new=0; //still in same number(we are still processing same number)
}
}
printf("Out of Loop \n");
count=i+1; //This gives correct count of numbers entered
for(i=0;i<count;i++) //to print numbers.
printf("%d ",input[i]);
return 0;
}
OUTPUT:-
E:>example.exe
78 2 65 998 1
assigning
assigning
space
assigning
space
.
.
.
space
assigning
Out of Loop
78 2 65 998 1