While Loop how to? - c++

I have a test in a couple of days and I was reviewing the study guide and I came across a question that I wasn't familiar with. It says "Write a while loop that continuously loops until the user inputs a number saved in a variable named myNum between -1 and -100. Use only < and > operators." Can someone give me a clear explanation of what exactly I am supposed to do for this question?

I'm honestly not entirely sure what this question is asking, because it seems a bit ambiguous in the wording, but this is what I would assume they are asking for. I'm not sure how you could get this done with "only" > and < operators, as you need input and possibly output operators (>> and << respectively). Anyway, I hope that this helps, and if its not perfectly correct with what your assignment is, maybe you can see the logic and make the small changes to have it fit better.
I commented each line, even the obvious (which is sort of a no-no when you get into heavier coding), this way all the syntax makes sense.
#include <iostream>
using namespace std;
int main()
{
// Initialize myNum to 1 so that it passes into while-loop
int myNum = 1;
// Continue looping as long if number is less than -100 or greater than -1 (terminating the loop when numbers from -100 to -1 are entered)
while((myNum > -1) || (myNum < -100))
{
// Display "Enter Text" to console
cout << "Enter number: ";
// Allow user to input number
cin >> myNum;
}
}

Related

Google Kickstart - Wrong answer if cout.clear() is not used

I find this very stupid to ask, but I've been trying a question on Google Kickstart (Round A, 2021).
Now, firstly, I'd like to clarify that I do NOT need help with the question itself, but I'm encountering a weird issue that seems to be compiler-related. This problem only arises on certain compilers.
I am posting the question link, then the question statement if someone does not wish to use the link, then the problem I'm facing along with the code that works and the code that doesn't work.
Question Title: K-Goodness String, Round A (2021)
Question Link: https://codingcompetitions.withgoogle.com/kickstart/round/0000000000436140/000000000068cca3
Problem
Charles defines the goodness score of a string as the number
of indices i such that Si ≠ SN−i+1 where 1≤i≤N/2 (1-indexed). For
example, the string CABABC has a goodness score of 2 since S2 ≠ S5 and
S3 ≠ S4.
Charles gave Ada a string S of length N, consisting of uppercase
letters and asked her to convert it into a string with a goodness
score of K. In one operation, Ada can change any character in the
string to any uppercase letter. Could you help Ada find the minimum
number of operations required to transform the given string into a
string with goodness score equal to K?
Input
The first line of the input gives the number of test cases, T. T
test cases follow.
The first line of each test case contains two integers N and K. The
second line of each test case contains a string S of length N,
consisting of uppercase letters.
Output
For each test case, output one line containing Case #x: y,
where x is the test case number (starting from 1) and y is the minimum
number of operations required to transform the given string S into a
string with goodness score equal to K.
Sample Input:
2
5 1
ABCAA
4 2
ABAA
Sample Output:
Case #1: 0
Case #2: 1
Explanation:
In Sample Case #1, the given string already has a goodness score of 1. Therefore the minimum number of operations required is 0.
In Sample Case #2, one option is to change the character at index 1 to B in order to have a goodness score of 2. Therefore, the minimum number of operations required is 1.
The issue:
The problem is fairly straightforward, however, I seem to be getting a wrong answer in a very specific condition, and this problem only arises on certain compilers, and some compilers give the correct answer for the exact same code and test cases.
The specific test case:
2
96 10
KVSNDVJFYBNRQPKTHPMMTZBHQPZYQHEEEQFQWOJHPHFBFXGFFGXFBFHPHJOWQFQEEEHQYZPQHBZTMMPHTKPQRNBYFFVDNXIX
95 7
CNMYPKORAUTSYETNXAZQZGBFSJJNMOMINYKNTMHTARUMDXAJAXDMURATHMTNKYNIMOMNJJSFBGZQZAXNTEYSTUAROKPKJCD
Expected Output:
Case #1: 6
Case #2: 3
The problem arises when I do NOT use std::cout.clear() at a very specific place in my code. Just printing the value of any random variable also seems to solve this issue, it doesn't necessarily have to be cout.clear() only. I'm pasting the codes below.
**Original Code (Gives incorrect answer):**
//
// main.cpp
// Google Kickstart - Round A (2021)
//
// Created by Harshit Jindal on 10/07/21.
//
#include <iostream>
#define endl "\n"
using namespace std;
int main() {
int num_test_cases;
cin >> num_test_cases;
for (int test_case = 1; test_case <= num_test_cases; test_case++) {
int answer = 0;
int N, K;
cin >> N >> K;
char s[N];
cin >> s;
int current_goodness = 0;
for (int i = 0; i < N/2; i++) {
if (s[i] != s[N-1-i]) { current_goodness++; }
}
answer = abs(current_goodness - K);
cout << "Case #" << test_case << ": " << answer << endl;
}
return 0;
}
Incorrect Result for original code:
Case #1: 6
Case #2: 6
Modified Code (With cout.clear() which gives correct answer):
//
// main.cpp
// Google Kickstart - Round A (2021)
//
// Created by Harshit Jindal on 10/07/21.
//
#include <iostream>
#define endl "\n"
using namespace std;
int main() {
int num_test_cases;
cin >> num_test_cases;
for (int test_case = 1; test_case <= num_test_cases; test_case++) {
int answer = 0;
int N, K;
cin >> N >> K;
char s[N];
cin >> s;
int current_goodness = 0;
for (int i = 0; i < N/2; i++) {
if (s[i] != s[N-1-i]) {
current_goodness++;
}
cout.clear();
}
answer = abs(current_goodness - K);
cout << "Case #" << test_case << ": " << answer << endl;
}
return 0;
}
Correct Result for modified code:
Case #1: 6
Case #2: 3
A few additional details:
This issue is NOT coming up on my local machine, but on Google Kickstart's Judge with C++17 (G++).
Answer for Case #2 should be 3, and NOT 6.
This issue does NOT come up if only the second test case is executed directly, but only if executed AFTER test case #1.
The issue is ONLY resolved if the cout.clear() is placed within the for loop, and nowhere else.
We don't necessarily have to use cout.clear(), any cout statement seems to fix the issue.
I know it's a long question, but given that a problem is only coming up on certain machines, I believe it would require a deep understanding of c++ to be able to understand why this is happening, and hence posting it here. I'm curious to understand the reasoning behind such a thing.
Any help is appreciated.
As pointed out by Paddy, Sam and Igor in the comments, here is the solution as I understand it:
The problem arises because char s[N] is NOT C++ standard, any variable length arrays, for that matter. That might cause a buffer overrun, and will write over memory outside of the array, causing all sorts of weird behaviour.
The best way to avoid these kinds of bugs is to make it logically impossible for them to happen. – Sam Varshavchik
In this case, using string s solved the issue without having to call cout.clear().
Also, using #define endl "\n" might be faster when redirecting output to files, but since we're importing the entire std namespace, any person who does std::cout will get an error because it'll essentially get translated to std::"\n" which does not make sense.

C++ - Using specific character input for 'if' statements

I am, for lack of a better word, an absolute programming novice. And as it stands, I've been flung head first into programming something in two or three languages.
As part of an assignment, we have been tasked with essentially recreating a heads/tails flip, in the form of a random chance game.
The way it works is the player has ten credits to start off with. They are asked to input a wager, and then they are asked heads or tails. Picking either heads or tails sets off a number generator, and depending on the value, they may well end up winning or losing their wager.
I coded a similar version of this using HTML/CSS/JS, and it works. I'll leave a puush link to the file so you can view it yourselves to get an idea of what I'm trying to do: http://puu.sh/bP2V7/2ef63f4a1c.html
I'm trying to do, functionally, the same thing in C++ in the form of a command application. I know the code I'm using works fine, and it compiles without much of a hitch. It's a bit annoying that it closes down rather than resetting to a previous line, but that's a hurdle I'll jump over when I get to it.
I had a look around, and to be honest, whilst a few of the things may well work, I'm admittedly relatively clueless and some of the programmer speak kinda flies over my head.
It's probably because I'm being thrown into it and I'm not used to it yet, but as it stands, I need your help.
My code simply works as follows (simplified to save time):
int main()
{
int points, wager;
points = 10;
output "HEADS OR TAILS?";
if (player has 1 point or more)
{
output "Input wager";
input wager value;
output "Wager is (player input)";
output "Heads or Tails?";
input h or t; //This was what I wanted
if (player selects 'heads') //For sake of simplicity, the code
{ //here will account for both heads
int heads; //and tails.
srand(NULL);
heads = random number 1 and 2;
if (heads = 1)
{
output "HEADS!";
output "You win 'wager'!";
points = points + wager;
}
if (heads = 2)
{
output "TAILS!";
output "You lose 'wager'!";
points = points - wager;
}
}
}
if (player has 0 points)
{
output "GAME OVER";
}
}
What I want to do is have the user input either an 'h' or a 't' to determine whether or not they want heads or tails.
In your programming class, they will have told you what they expect you to use as tools for input and output, eg char inputChar; cin >> inputChar; or similar. Use whatever they told you to use in the style they want you to use, eg
cout << HEADS_OR_TAILS_PROMPT;
char inputChar;
cin >> inputChar;
switch(inputChar) {
case 'h':
{
... // code for the heads case
break;
}
case 't':
{
... // code for the tails case
break;
}
default:
// whatever you want to do if they didn't input a valid option
}
Although, to be honest, asking your professor is going to get you a better answer for what the grader is expecting than asking us is.

C++ simple If statement making the rest of the program not execute

I have an assignment where I must read from a file and perform various calculations on it and write the answer to an output file. Everything was going great until I came to this step:
"Reread the file and compute the sum of the integers in the file as long as the sum does not exceed 1000. Use a flag controlled loop structure."
My code snippet is as follows:
dataFile2.close();
dataFile2.clear();
dataFile2.open("J:\\datafile2.txt");
sum = 0;
while(sum < 1000)
{
dataFile2 >> num;
sum = sum + num;
if(sum > 1000)
sum = sum - num;
}
answers << "The sum of the integers not exceeding 1000 is " << sum << endl;
cout << "The sum of the integers not exceeding 1000 is " << sum << endl;
return 0;
My variables have already been declared. when I take out the if statement the sum adds the last number and the sum then exceeds 1000. When the If statement is left in, the answers and cout statements are not executed and there are no compiler warnings or errors.
Any help on this would be greatly appreciated.
-ThePoloHobo
Since no one seems to want to give you a correct answer... (and
to be fair, it's hard to give a correct answer without actually
doing your work for you).
There are two issues in you code. The first is the requirement
that you use a flag. As I said in my comment, the idiomatic
solution would not use a flag, but there's no problem using one.
A flag is a boolean variable which will be tested in the
while, and will be set in a conditional in the loop, when you
find something that makes you want to leave the loop.
The second issue is that you are using num without checking
that the input has succeeded. You must check after the >>
operator. The idiomatic way of checking (and the only thing
that should ever be used by someone not experienced in the
language) is to treat the stream as if it were a boolean:
dataFile2 >> num;
if ( dataFile2 ) {
// Input succeeded...
} else {
// Input failed for some reason, maybe end of file
}
Since all operations on a stream return a reference to the
stream, it is usual to merge the test and the input:
if ( dataFile2 >> num ) {
// succeeded
} else {
// failed
}
(Personally, I find the idea of modifying state in the condition
of an if or a while horrible. But this idiom is so
ubiquitous that you should probably use it, for the simple
reason that that's what everyone expects.)
In pedagogical environments, it's probably acceptable to
consider any failure to be end of file, and just move the test
up into the while (except, of course, that you've been asked
to use a flag). In other contexts, you'll want to take into
account the fact that the failure could be due to a syntax error
in the input—someone inserted "abc" into the file where
you were expecting a number. There are a number of ways of
handling this, all of which are beyond the scope of what you are
trying to do, but be aware that after you've detected failure,
you can interogate the stream to know why. In particular, if
dataFile2.eof() is true, then the failure was (probably) due
to you having read all of the data, and everything is fine. (In
other words, failure to read a data is not necessarily an error.
It can be simply end of file.)
You don't seem to be using a flag variable, which could help in this case. Something like this should fix it:
sum = 0;
bool sumUnder1000 = true; //Or the C++ equivalent, I'm a bit rusty
while(sumUnder1000)
{
if(!dataFile2.good()){
sumUnder1000 = false; //We've reached end of file or an error has occurred
return;
}
dataFile2 >> num;
sum = sum + num;
else if(sum > 1000){
sum = sum - num;
sumUnder1000 = false;
}
}

How can I properly set a condition for an specific space in array?

I'm Developing an small app for practice purposes in C++, I actually suceeded developing this algorithm without using arrays, but right now I want to do it using an Array. The program should accept four grades 2 of 15 points practices (First and third value), two of 20 points (Second and fourth values) and one of 30 points. this is my code:
int main(int argc, char** argv){
int grades[5];
int i;
int sum=0;
for(i=0; i<5; i++){
cin >> grades[i];
sum+=grades[i];
if(grades[0]>15||grades[1]>20){
cout<<"ERROR"<<endl;
break;
}else if(grades[2]||grades[3]){
cout<<"ERROR"<<endl;
break;
}if(grades[4]>30){
cout <<"ERROR"<<endl;
break;
}
}
}
The issue here is that it should not be printing Error on console and break it from continuing, only if the condition is met, at this point if I input values even within the condition's grace, it prints out "Error" and stops.
I'm not really looking for someone to solve this issue, I'm looking to know what I'm doing wrong without getting someone to solve it for me, in proper words, I'm looking for tips/hints.
This line here
}else if(grades[2]||grades[3]){
cout<<"ERROR"<<endl;
break;
}
will cause your error to display at any time your elements at indices 2 or 3 are non zero. You dont initialise your array elements so it is quite possible that the values are nonzero when your loop starts. To ensure that they are not, you could assign zero to all elements before you start. I am not sure what your code is trying to do, but when the user enters anything other than zero for the cin at i = 2 and i = 3 your loop will break with error output (assuming that the first if confition in your if-else block is not satisfied but if that condition was satisfied your loop would also exit anyway)

C++ input of type char, output of type int

I am taking my very first C++ class and I am stuck. I would really appreciate some help from you experienced programmers.
The assignment is creating a blackjack-scoring program. Not a very realistic one, but hey. The user inputs how many cards he wants and then the values of each of those cards. The assignment specifies that the inputs should be in type char. So if the user has a 2 card they enter 2, but that 2 is actually char and must be converted to int. Or they would enter "Q" if they have a queen and my program is supposed to convert that Q to ten points for scoring. I cannot figure out what is the right way to do this. The assignment suggests I will use either a switch statement or nested if-else statement, but I am afraid I don't understand switch very well from the book examples.
So here's a tiny bit of my attempts at switch. *points_for_card* is of type char and *number_value* is int.
switch (points_for_card)
{
case '2':
number_value = 2 ;
break;
case '3':
number_value = 3 ;
break;
// ETC
}
So what I am going for here is: if the user enters '3' as a char, it becomes int 3. But maybe this is not how switch works at all.
The thing is, my program compiles and works, but returns weird crazy huge numbers. If I move points_for_card to int instead of char, then the arithmetic works perfectly for whatever numbers I enter, because at that point it's just adding them together.
I hope I explained this ok, will clarify as much as possible if necessary.
it can be something like this code:
if (points_for_card >= '1' && points_for_card <= '9'){
number_value = points_for_card - '0'; // convert to number
}else if (points_for_card == 'Q'){
...
}
A map comes to mind. You can store the scores directly, or you can make one map to look up the card type and other maps to associate other information (like score) to each card. Here's the baby example:
std::map<char, int> scores;
scores['Q'] = 10; scores['A'] = 13; scores['2'] = 2; // etc.
char c;
std::cout << "Please enter a card: ";
std::cin >> c;
std::cout << "Your card has score " << scores[c] << std::endl;
Oftentimes when your heart says "switch", your brain should say "map" :-)
Personnally I'd define an enum ECardType { Card_2, ..., Card_10, Card_Jack, ... }; and have one map be std::map<char, ECardType>, and then other maps from card type to secondary information like scores.
How are you taking inputs into points_for_card ?
Your input should be cin >> points_for_card;
Instead of comparing a character to a character, you can also compare it to the ASCII value of a character.
For example,
char letter = 'A'
if(letter == 65){
cout << "Match";
}
The above code will output "Match!".
Also, your switch statements are perfectly worded. The problem lies elsewhere in your program, so please provide the relevant source.
Another point related to your program but not your problem: How are you dealing with Aces ? You know that they can be counted as either 1 or 11, depending on the player's hand value, right ?