This question already has answers here:
Why is cout printing twice when I use getline?
(2 answers)
Closed 5 years ago.
When I run this and after I select my number as a player, Computer returns me two outputs (instead of one...). I have no idea why, could you please help me explain why that happens?
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
int random(int a, int b)
{
int num = a + rand() % (b + 1 - a);
return num;
}
int main()
{
srand(time(NULL));
int myNum;
cout << "Choose your number, human: ";
cin >> myNum;
int min = 1;
int max = 100;
int comp;
string player;
while(1) {
comp = random(min, max);
cout << "Computer: " << comp << endl; // why does this get called twice??
getline(cin, player);
if (player == "too high") {
max = comp - 1;
cout << "min: " << min << " max: " << max << endl;
} else if (player == "too low") {
min = comp + 1;
cout << "min: " << min << " max: " << max << endl;
} else if (player == "correct") {
cout << "Computer found the number..." << endl;
break;
}
}
}
It's because you are mixing input using >> and getline. getline reads to the next newline, >> does not. After you have entered your number, there is still a newline left behind, you have typed it, but hasn't yet been read. The first time you call getline that left behind newline gets read, and the program doesn't pause. Only on the second time that you call getline does your program pause and wait for you to type something.
Simple way to fix the problem is
int myNum;
cout << "Choose your number, human: ";
cin >> myNum;
// flush pending newline
string dummy;
getline(cin, dummy);
Related
My program will repeat output: "You are currently on the 2 floor out of 5
The sum of the codes is: 7 and the product of the codes is: 12
Try again before he catches onto you!"
Based on how many wrong characters are added how can I fix this? I have inserted the cin.clear and cin.ignore but it will repeat the part above.
i.e. if I type wasds it will repeat 5x. Any other notes are also appreciated.
#include <iostream>
#include <ctime>
using namespace std;
int PlayerLevel = 0;
int MaxLevel = 5;
bool GamePlay ()
{
srand(time(NULL));
int PlayerGuessA, PlayerGuessB, PlayerGuessC;
int CodeA = rand() % PlayerLevel + PlayerLevel;
int CodeB = rand() % PlayerLevel + PlayerLevel;
int CodeC = rand() % PlayerLevel + PlayerLevel;
int SumofCodes = CodeA + CodeB + CodeC;
int ProductofCodes = CodeA * CodeB * CodeC;
cout << "You are currently on the " << PlayerLevel << " floor out of 5" << endl;
cout << "The sum of the codes is: " << SumofCodes << " and the product of the codes is: " << ProductofCodes << endl;
cin >> PlayerGuessA >> PlayerGuessB >> PlayerGuessC;
int PlayerProduct = PlayerGuessA * PlayerGuessB * PlayerGuessC;
int PlayerSum = PlayerGuessA + PlayerGuessB + PlayerGuessC;
if (PlayerProduct == ProductofCodes && SumofCodes == PlayerSum) {
cout << "Great Job you got this!!!\n" << endl;
++PlayerLevel;
return true;
}
else
{
cout << "Try again before he catches onto you!\n" << endl;
return false;
}
}
int GameStart()
{
string Introduction = "Welcome to your worst nightmare. You are trapped in a murderer's house. You are on the 5th floor and need to get to the first floor to escape.\n";
string Instructions = "He has each door locked behind a security system that requires a 3 number code to disarm it.\nEnter the codes and move foward. Each level will the code will be harder to figure out.\n";
string PlayerStart;
cout << Introduction << endl;
cout << Instructions << endl;
cout << "Would you like to escape? Yes or No" << endl;
cin >> PlayerStart;
if (!(PlayerStart != "Yes" && PlayerStart != "yes")) {
++PlayerLevel;
}
return 0;
}
int main ()
{
if (PlayerLevel == 0) {
GameStart();
}
while (PlayerLevel <= MaxLevel)
{
bool bLevelComplete = GamePlay();
cin.clear ();
cin.ignore();
}
cout << "You Made it out! Now run before he finds out!" << endl;
return 0;
}
When the type of the input doesn't match the type of the variable that it is being extracted to, cin sets the fail bit. Once this happens, all subsequent reads fail until the stream is reset. The offending characters are still left in the buffer, so that needs to be cleared out as well.
Your usage of cin.clear() and cin.ignore() meant that the fail bit was getting reset, but only one offending character was being removed (cin.ignore() ignores one character by default). This is why you saw the output repeating x times for x erroneous characters.
You could do something like this:
while (PlayerLevel <= MaxLevel)
{
bool bLevelComplete = GamePlay();
if (cin.fail())
{
//Input extraction failed, need to reset stream and clear buffer until newline
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
}
}
Please disregard some of the undeclared variables. I do not really know what is wrong.
#include <iostream>
using namespace std;
int main()
{
int number{}, tries{}, ans{}, count{};
cout << "Enter an integer greater than 0: ";
cin >> number;
while (number > 0){
ans = number / 10;
++count;
if (ans == 0){
cout << "The number has " << count << "digits";
break;
}
}
return 0;
}
You're never actually changing number, so every iteration, you set ans to the same thing and run the same test.
As indicated by others, you are not updating the loop variable (number) anywhere inside the loop. Hence it is very likely to get in an infinite loop. Here is a sample updated code you can try out.
#include <iostream>
using namespace std;
int main()
{
int number{}, tries{}, ans{}, count{};
cout << "Enter an integer greater than 0: ";
cin >> number;
if (number<=0){
cout << "Incorrect input.";
}
else{
while (number>0){
number = number / 10;
count ++;
}
cout << "The number has " << count << " digits";
}
return 0;
}
Can you help me guys? I'm a total beginner. My code worked fine then KEEP LOOPING FOREVER and never goes back to or cmd would crash with "Process terminated with status -1073741676". It should loop once then CIN >> again. It happens when I enter 10 digit numbers in my CIN >>.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class noteAssign { //This class return "A" if the random number generated is between 1 and 10
public:
int x;
int noteOut(int x){
if(x>1 && x<10){
cout << "ITS A" << endl;
return x;
}else{
cout << "IT'S NOT A" << endl;
return x;
}
}
}gonote;
int main()
{
cout << "Match the note's Hertz!" << endl;
cout << "Your answer may range from 1 to 20" << endl;
cout << "Type 0 to quit" << endl;
int noteIn; //No real purpose YET
do {
srand(time(0)); //ADDING MULTIPLE RAMDOMIZER FOR WIDER RANDOM RANGE
int rand1 = 1+(rand()%20); //randomizer 1
int rand2 = 1*(rand()%20); //randomizer 2
int hzout = (rand1 * rand2 + rand1 / rand2)%20; //rand 3
noteAssign gonote;
cout << gonote.noteOut(hzout) << endl; //calls the function and gives the parameter
cin >> noteIn; //No real purpose YET
} while(noteIn != 0); //program quits when you enter "0"
};
I cannot figure out why my getchar() function is not working the way I want it to work. I am getting 10 not 2. Please take a look.
Main():
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int var, newvar;
cout << "enter a number:" << endl;
cin >> var;
newvar = getchar();
cout << newvar;
return 0;
}
Here is my output:
enter a number:
220
10
Ultimately though I need to be able to distinguish between a '+' '-' or letter or number.
This is maybe not the cleanest way to do it but you can get every char one by one :
#include <iostream>
using namespace std;
int main()
{
int var;
cout << "enter a number:" << endl;
cin >> var;
std::string str = to_string(var);
for(int i=0; i < str.length();++i)
cout << str.c_str()[i] << endl;
return 0;
}
If you enter for example: "250e5" it will get only 250 and skip the last 5.
Edit:
This is just a simple parser and does not do any logic.
If you want to make a calculator I would recommend you to look at what Stroustrup did in his book the c++ programming language.
int main()
{
string str;
cout << "enter a number:" << endl;
cin >> str;
for(int i=0; i < str.length();++i) {
char c = str.c_str()[i];
if(c >= '0' && c <= '9') {
int number = c - '0';
cout << number << endl;
}
else if(c == '+') {
// do what you want with +
cout << "got a +" << endl;
} else if(c == '-')
{
// do what you want with -
cout << "got a -" << endl;
}
}
return 0;
}
i have the next code which asks the user for a really long number like 100000000 and then it prints how many times a given digit appears on that number, the code works fine and does everything correctly, but the professor told me that i dont have to use strings or chars, but when the code asks the user for a number it necessarily needs a string and i donĀ“t know how to modify it, i used the gmp library
#include <iostream>
#include <stdio.h>
#include <gmp.h>
#define MAX 40
using namespace std;
void searchDigit(FILE *fd);
int NewNumber();
int main()
{
FILE *fd;
int otherNumber;
string text;
mpz_t num;
do
{
if((fd = fopen("File.txt","w+"))!= NULL)
{
mpz_init(num);
cout << "Give me the number: " << endl;
cin >> text;
mpz_set_str(num,text.c_str(),10);
mpz_out_str(fd,10,num);
fclose(fd);
searchDigit(fd);
otherNumber = NewNumber();
}
else
cout << "Fail!!" << endl;
}while(otherNumber);
return 0;
}
void searchDigit(FILE *fd)
{
int car,continue = 1,r;
char answer,digit;
if((fd = fopen("File.txt","r"))!= NULL)
{
do
{
r = 0;
fseek(fd,0,SEEK_SET);
cout << "What digit do you want to search? " << endl;
cin >> digit;
while((car = fgetc(fd))!= EOF)
{
if(car == digit)
r++;
}
cout << "The digit x=" <<digit<< " appears " << r << " times" << endl;
cout << "Do you want to search any other digit? " << endl;
cin >> answer;
if(answer != 'S')
continue = 0;
}while(continue);
}
else
cout << "Fail!!" << endl;
}
int NewNumber()
{
char answer;
cout << "DO you wish to work with a new number? " << endl;
cin >> answer;
if(answer == 'S' || answer == 's')
return 1;
else
return 0;
}
Thanks in advance
Depends on how big your input might actually be... but for retrieving digits you could do something like:
#include <iostream>
using namespace std;
typedef unsigned long long UINT64;
int main() {
UINT64 i;
std::cin >> i;
while (i >= 1) {
int digit = i % 10;
std::cout << digit << " ";
i /= 10;
}
}
input: 18446744073709551614
outputs: 4 1 6 1 5 5 9 0 7 3 7 0 4 4 7 6 4 4 8 1