how to get output when user just presses enter in c++ - c++

I am trying to build a simple code that gives the coordinates in two dimensions after you put some direction input.
The problem is I don't know how to give the proper output when the user just presses enter. This should be (0,0) because if the user just presses enter it means he has not changed the coordinates. How can I know if the user has just pressed enter and give the proper output accordingly?
This is the code I have done:
#include <iostream>
using namespace std;
int main ()
{
int a = 0, b = 0;
string direction;
if( cin >> direction) {
if( !direction.empty() ) {
// handle input correctly
// Interpret directions
for (int i = 0; i < direction.length(); i++) {
if (direction[i] == 'e') a++;
else if (direction[i] == 's') b++;
else if (direction[i] == 'w') a--;
else if (direction[i] == 'n') b--;
}
}
else if (direction.empty()) cout << "(0,0)" << endl;
}
// Output coordinates
cout << "(" << a << "," << b << ")" << endl;
}

The operation cin >> direction; ignores spaces and also empty lines. Here the string direction is not empty whitespace terminated word.
It is possible to read entire line using std::getline. This function reads line from stream and also it reads empty lines.
So, the solution:
int a = 0, b = 0;
string direction;
getline(cin, direction);
if(!direction.empty()) {
// Interpret directions
for (int i = 0; i < direction.length(); i++) {
if (direction[i] == 'e') a++;
else if (direction[i] == 's') b++;
else if (direction[i] == 'w') a--;
else if (direction[i] == 'n') b--;
}
}
// else is not needed, since here a = 0 and b = 0.
// Output coordinates
cout << "(" << a << "," << b << ")" << endl;

What you need to do is wrap an if around your attempt to get input, then if that succeeds, check whether or not the string the input is put in is empty or not. If it is empty you know that the user pressed enter without giving any other input. In code that would be something like:
if( cin >> input) {
if( !input.empty() ) {
// handle input correctly
}
}
If you want to know why it's done that way, google it in the "C++ super FAQ" at isocpp.org.

Related

Failing Tictactoe in c++

I'm a beginner in c++, i'm trying to make a tictactoe. My program fails at the part acfter i enter input. When I enter an input, there is no next action from the program like i expected it to ("unvalid", check if win or loose, ask for input again). It only shows blank. like below: after I enter "1", nothing happens, and I can keep enter more input.
terminal example photo
I know it is a simple activity but I just ca't figure it out ToT. Thank you for helping!
//tictactoe
#include <iostream>
#include <vector>
using namespace std;
//declared variables
vector<char> out = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
int in = 2;
char player_out;
bool loose = false;
char x;
bool filled = false;
bool end(){ //won yet?
bool loose = false;
//horizontal
if (out[1] == out[2] && out[3] == out[2]){
loose = true;
}
else if (out[4] == out[5] && out[6] == out[5]){
loose = true;
}
else if (out[7] == out[8] && out[9] == out[8]){
loose = true;
}
//vertical
else if (out[1] == out[4] && out[7] == out[1]){
loose = true;
}
else if (out[2] == out[5] && out[8] == out[2]){
loose = true;
}
else if (out[3] == out[6] && out[9] == out[3]){
loose = true;
}
else if (out[1] == out[5] && out[9] == out[5]){
loose = true;
}
else if (out[3] == out[5] && out[7] == out[5]){
loose = true;
}
else{
loose = false;
}
return loose;
}
void game_start_display(){ //display the board
cout << "TIC TAC TOE\n";
cout << " | | \n";
cout << " " << out[1] << " | " << out[2] << " | " << out[3] << " \n";
cout << "______|______|______\n";
cout << " | | \n";
cout << " " << out[4] << " | " << out[5] << " | " << out[6] << " \n";
cout << "______|______|______\n";
cout << " | | \n";
cout << " " << out[7] << " | " << out[8] << " | " << out[9] << " \n";
cout << " | | \n\n";
}
int change_player(){ //take turn 1st and 2nd player
if (in == 1){
in++;
}
else{
in--;
}
return in;
}
bool filled_f() { //check if the spot is filled
if (out[x] != 'X' and out[x] != 'O'){
filled = true;
out[x] = player_out; //fill the input into the spot
}
else if (out[x] == 'X' or out[x] == 'O')
cout << "The square has already been used!\n";
filled = false;
return filled;
}
char player_out_f(){ //change output sign for each players (X, O)
if (in == 1){
player_out = 'X';
}
else if (in == 2){
player_out = 'O';
}
return player_out;
}
void c_player_display(){ //tell players to enter a number
cout << "Player " << in << "'s turn, please enter a number:\n";
}
int main(){
//intro
int loose = false;
game_start_display();
while(loose == false){ //when the game is still happening
change_player(); //change player (player start is set 2 so this comes first and change it to 1)
player_out_f(); //change player output sign (X, O)
c_player_display(); //print the line to ask for input
while(filled == false){ //when the there is no input yet (the spot is not filled)
cin >> x; // input
if (x > 0 && x < 10){ //check if input is in range 1-9
filled_f(); //check if the spot is occupied
}
else if(x < 0 && x > 10) { //if input is out of range
cout << "Invalid! Enter again!\n";
filled = false; //repeat the asking input circle (the while)
}
}
game_start_display(); //output the board again with new char (X or O)
end(); //check if anyone's won yet, if no, repeat the circle
}
cout << "Player " << in << " won! GG";
}
You have infinite loop at while (filled == false) { ... }, because filled_f always sets filled to false (and the else if branch of the condition inside this loop as well does so). It's because you most likely missed figure brackets when writing else if block in filled_f. Your indentation hints that you wanted 2 statements to be in that block, but as of now, only the first is executed conditionally, and the second (filled = false;) is executed after the branch. In other words, with intuitive indentation this function looks like this:
bool filled_f() { //check if the spot is filled
if (out[x] != 'X' and out[x] != 'O') {
filled = true;
out[x] = player_out; //fill the input into the spot
}
else if (out[x] == 'X' or out[x] == 'O')
cout << "The square has already been used!\n";
filled = false;
return filled;
}
It sets filled = false; in any case, since if/else execute (depending on condition) the statement immediately following one of them (see here), and indentation is ignored (unlike in, e.g., Python, where indentation alone determines boundaries of conditions, loops, function etc), so only cout << ... is conditionally executed. To do what you want put figure brackets around appropriate statements the same way you already did for the first if branch to create compound statement (block) from them, which is a statement itself and does what you want - groups several other statements within it, executed in sequence:
bool filled_f() { //check if the spot is filled
if (out[x] != 'X' and out[x] != 'O') {
filled = true;
out[x] = player_out; //fill the input into the spot
}
else if (out[x] == 'X' or out[x] == 'O') {
cout << "The square has already been used!\n";
filled = false;
}
return filled;
}
Additional remarks
Note that logically it's not needed to have if condition in else since if the first if condition is dissatisfied, else if condition is definitely satisfied (look De Morgan's Laws) and you can just write else:
// ...
else {
cout << "The square has already been used!\n";
filled = false;
}
// ...
Also in your main loop, you use this:
if (x > 0 && x < 10){ //check if input is in range 1-9
filled_f(); //check if the spot is occupied
}
else if(x < 0 && x > 10) { //if input is out of range
cout << "Invalid! Enter again!\n";
filled = false; //repeat the asking input circle (the while)
}
to test whether x is within range, but your condition in else if is wrong (should be x <= 0 || x >= 10 instead of x < 0 && x > 10) and can be omitted altogether (again see De Morgan's Laws) by using just else.

How to get multiple input with char and multiple output with int? C++

I'm quite new to C++, so I apologize if I am not sounding technical. I am having a little trouble getting a multiple input and output with my code, I'm thinking I should have a loop to get the data but i'm not sure how i'd go about that in my code, I've thought about using getline() but that doesn't seem to want to work with Char.
I've tried getline but I'm not sure how to implement it with the Char input, I believe I may need a separate loop as well but again not too sure. I'm thinking it could be done to EoF as well.
Here's my code:
int main()
{
char inpval;
int outval = 0;
cout << "Enter a Roman Number to convert: " << endl;
while (cin.get(inpval))
{
inpval = toupper(inpval);
if (inpval == 'M')
outval = outval + 1000;
else if (inpval == 'D') {
inpval = cin.peek();
inpval = toupper(inpval);
if (inpval == 'M') {
outval = outval - 500;
continue;
} else {
outval = outval + 500;
continue;
}
}
//etc
cout << "The Equivalent Arabic value is:" << endl;
cout << outval << "\n";
return 0;
}
My expected output is:
(All on newline)
Input:
I
II
IV
V
VI
Output:
1
2
4
5
6
Actual output is:
Input:
I
Output:
1
P.S: The program converts Roman Numeral chars to their respected number.
Any help is appreciated!
You can take input multiple items from cin, using below syntax.
cin >> a;
cin >> b;
cin >> c;
Another way is also there
cin >> a >> b >> c;
This technique is called "operator chaining" which is similar to the above.
Do you have any problem doing it like this?
cout << "Enter a Roman Numeral" << endl;
string inpval;
cin >> inpval;
while (inpval != "exit")
{
int outval = 0;
if (inpval == "I")
outval = 1;
else if (inpval == "II")
outval = 2;
else if (inpval == "III")
outval = 3;
else if (inpval == "IV")
outval = 4;
// ect
cout << "The Equivalent Arabic value is: " << outval << endl << endl;
cout << "Enter next numeral: (type exit to exit) " << endl;
cin >> inpval;
}
Method 1: Use getchar(), Calculate/Convert Roman to integer until you encounter a space ' ',when you get a space ' ' output the integer and do the same next roman number until you get another space ' ' or newline '\n' and stop the program once you encounter newline '\n'.
Method 2:Use type std::string and take input with getline. Then iterate through the string and calculate until you find space ' ' output the number, do the same till you find next space ' ' or end when string ends.
If you know # of Roman numbers you want to convert you can put it in a loop.
Hope this helps.
Example(Method 2)
#include <bits/stdc++.h>
int value(char r)
{
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
}
int main()
{
int out=0;
std::string s;
std::string::iterator i; //string iterator
//for more info go to https://www.geeksforgeeks.org/stdstring-class-in-c/
getline(std::cin,s);
for (i = s.begin(); i!= s.end() ; ++i)
{
if(*i != ' ')//Encounter a space, output result and
{ //go to next roman numeral
int s1 = value(*i);
if (*(i+1) != ' ' || *(i+1) != '\0')
{
// Getting value of i+1 nth Element
int s2 = value(*(i+1));
// Comparing both values
if (s1 >= s2)
{
// Value of current symbol is greater
// or equal to the next symbol
out = out + s1;
}
else
{
out = out + s2 - s1;
i++; // Value of current symbol is
// less than the next symbol
}
}
else
{
out = out + s1;
i++;
}
}
else
{
std::cout<<out<<" ";
out = 0;
}
}
std::cout<<out<<" ";
std::cout<<std::endl;
return 0;
}
Input:
I II MM MCMIV
Output:
1 2 2000 1904

Can someone tell me why I am stuck in my validation loop after entering 'y' to continue?

Why am I getting stuck in my validation loop after hitting Y to continue? I have to use cin.get and can not use strings
This program collects input from a user and displays them by using a pointer with an array, I have to validate for negative numbers, letters and newline characters with the appropriate message
#include <iostream>
#include <iomanip>
using namespace std;
void validateUserInput(char *userInputCharArray, int &strLength);
int const ARRAY_SIZE = 100;
int main()
{
char *userInputCharArray = nullptr;
char yes = NULL;
int lengthOfInput;
//creating a dynamic array size 100
userInputCharArray = new char[ARRAY_SIZE];
//loop
do
{
int count = 0;
//user prompt and accept input
cout << "Please enter an integer >= 0 and press <ENTER>: " << endl;
cin.get(userInputCharArray, ARRAY_SIZE);
while(userInputCharArray[count] != ' ' && userInputCharArray[count] != '\0')
count++;
{
if(userInputCharArray[count] == ' ')
{
userInputCharArray[count] = '\0';
}
}
lengthOfInput = count;
validateUserInput(userInputCharArray, lengthOfInput);
cout << "Your number is: " << endl;
for(int i = 0; i < lengthOfInput; i++)
{
cout << userInputCharArray[i] - '0' << " ";
}
cout << endl;
cout << "Press y to continue or any other button to exit: " <<endl;
cin >> yes;
delete [] userInputCharArray;
userInputCharArray = nullptr;
userInputCharArray = new char[ARRAY_SIZE];
}while(yes == 'y' || yes == 'Y');
cout << "Thank you Good-Bye";
cout << endl;
delete [] userInputCharArray;
userInputCharArray = nullptr;
system("pause");
return 0;
}
Im getting stuck in my functions while loop
void validateUserInput(char *userInputCharArray, int &strLength)
{
int counter = 0;
while(*userInputCharArray < '0' || (*userInputCharArray >= 'A' && *userInputCharArray <= 'Z')
|| (*userInputCharArray >= 'a' && *userInputCharArray <= 'z')
|| *userInputCharArray == 0)
{
cout << "Please enter a positive integer and press <ENTER>: " <<endl;
cin.get(userInputCharArray, ARRAY_SIZE);
}
while(userInputCharArray[counter] != ' ' && userInputCharArray[counter] != '\0')
counter++;
if(userInputCharArray[counter] == ' ')
{
userInputCharArray[counter] = '\0';
}
strLength = counter;
}
According to the while loop you have here, you will keep on calling in.get so long as the first character that you read in is a digit or an alphabetic character. So, if you start your input with one of those characters, you will loop forever.
I'd suggest that you get input a line at a time and then parse what you get.
cin.get(*userInputCharArray);
Will extract one character only, therefore the terminator character '\0' will not be part of userInputCharArray.
Change it to read a line at a time and parse the input. If you're still having issues, you can flush your input buffer before each read like so:
cin.ignore(10, "\n");
cin.get(userInputCharArray, ARRAY_SIZE);

C++ Function being called when it isn't supposed to

I'm nearly finished working on a small guessing game, but i have run into a problem I don't know how to work around.
The problem is with the check_guess function that is checking to make sure the guess being input is a number between 1 and 100.
When running the program the first time, everything works fine.
http://i.imgur.com/pprunDT.png (I would post images if my reputation weren't so low)
But every time after, where yes to play again is chosen, the program runs through the check_guess function and displays "Invalid Input" when it shouldn't
http://i.imgur.com/8OSnSJt.png
I'm not sure why the program is behaving this way.
The code for the entire program is here:
#include <iostream>
#include <cstdlib> //for rand
#include <ctime> //for time
#include <string>
#include <sstream> //for conversions from string to int
using namespace std;
int check_guess(int tries) { //function for limiting the input of guess
string guess = "";
int result = 0;
do {
getline (cin, guess);
istringstream convert(guess);
if ( !(convert >> result) || (result < 1 || result > 100) ) {
result = 0;
cout << "Invalid Input.\n" << endl;
cout << "You have " << tries << " tries: ";
}
} while (result == 0);
return result;
}
bool play_again() { //function for limiting the input of mode
bool quit;
string yn;
do {
cin >> yn;
if ( yn == "y" || yn == "yes" ) {
quit = false;
}
else if ( yn == "n" || yn == "no" ) {
quit = true;
}
else {
yn = "invalid";
cout << "Invalid input.\n\nEnter 'y' or 'n': ";
}
} while ( yn == "invalid" );
return quit;
}
int main()
{
srand(time(0)); //sets seed to be random
int mystery = 0; //defines mystery number
int guess = 0; //defines guess
int tries = 5; //defines trys
bool quit = false; //defines replay or quit
cout << "----------------------------------\n";
do { //while mode is not set to quit, keep playing
tries = 5; //resets tries each new game
mystery = rand() % 100 + 1; //sets mystery number to be random
guess = 0;
cout << "Pick a number between 1 and 100.\n\nYou have 5 tries: ";
while (tries != 0) { //loops until you have no tries left
guess = check_guess(tries);
if (guess == mystery) { tries = 0; } //if you guess right it ends the loop
else { tries--; } //guessing wrong lowers tries by 1
if ( tries != 0 && guess > mystery) {
cout << guess << " is too high.\n" << endl;
cout << "You have " << tries << " tries: ";
}
if ( tries != 0 && guess < mystery) {
cout << guess << " is too low.\n" << endl;
cout << "You have " << tries << " tries: ";
}
}
if (guess == mystery) { //if guess == mystery by time loop ends you win
cout << "Got it! You Win!\n" << endl;
}
else { //if not, you lose
cout << "You Lose! The number was: " << mystery << ".\n" <<endl;
}
cout << "-------------------\n";
cout << "Play Again?(y/n): "; //ask user to play again
quit = play_again();
cout << "-------------------\n";
if (quit == false)
cout << endl;
} while (quit == false);
cout << "----------------------------------" << endl;
return 0;
}
I'm not sure how to fix this.
this line:
cin >> yn;
only reads the 'y' but not the end of line. As a result, the next execution of this instruction
getline (cin, guess);
initializes guess to an empty string.
On line 19, import the code "cin.ignore();" without quotations.
So your code reads as
`int check_guess(int tries) { //function for limiting the input of guess
string guess = "";
int result = 0;
do {
getline (cin, guess);
istringstream convert(guess);
if ( !(convert >> result) || (result < 1 || result > 100) ) {
result = 0;
cin.ignore();
cout << "Invalid Input.\n" << endl;
cout << "You have " << tries << " tries: ";
}
} while (result == 0);
return result;
}
`
and so on. This stops input into the console briefly. You're code is reading the 'y' to try again as the input for the number when you restart as well. Putting in the little line cin.ignore(), stops it from inputting y twice.
Change play_again() to:
bool play_again() { //function for limiting the input of mode
bool quit;
string yn;
do {
getline (cin, yn);
if ( yn == "y" || yn == "yes" ) {
quit = false;
}
else if ( yn == "n" || yn == "no" ) {
quit = true;
}
else {
yn = "invalid";
cout << "Invalid input.\n\nEnter 'y' or 'n': ";
}
} while ( yn == "invalid" );
return quit;
}

probably wrong if statement, not moving to next row after input

When I run my program, I have to type how many rows do I want in my output. I have a limit from 1 to 100 rows. Each row is a task with a name of the task followed by increasing number, example: Task1:, Task2, .... When I type something into input, it must convert input string /see the code below - except the code in main();/.
My problem is that when I type first input, it should go to next task/next row/ but it doesnt. I type for example 10 strings but they dont go each to next task but they stay in one task..hope you understand now.
#include<iostream>
#include<string>
#include <ctype.h>
using namespace std;
void Convert(string input){
string output = "";
string flag = "";
bool underscore = false;
bool uppercase = false;
if ( islower(input[0]) == false){
cout << "Error!" <<endl;
return;
}
for (int i=0; i < input.size(); i++){
if ( (isalpha( input[i] ) || (input[i]) == '_') == false){
cout << "Error!" <<endl;
return;
}
if (islower(input[i])){
if (underscore){
underscore = false;
output += toupper(input[i]);
}
else
output += input[i];
}
else if (isupper(input[i])){
if (flag == "C" || uppercase){
cout << "Error!"<<endl;
return;
}
flag = "Java";
output += '_';
output += tolower(input[i]);
}
else if (input[i] == '_'){
if (flag == "Java" || underscore){
cout << "Error!" <<endl;
return;
}
flag = "C";
underscore = true;
}
}
cout << output <<endl;
}
int main(){
const int max = 100;
string input;
int pocet_r;
cout << "Zadaj pocet uloh:" << endl;
cin >> pocet_r;
if(pocet_r >= 1 && pocet_r <=100)
{
for (int i = 0; i <pocet_r; i++)
{
cout << "Uloha " << i+1 << ":" << endl;
while (cin >> input)
Convert (input);
while(input.size() > max)
cout << "slovo musi mat minimalne 1 a maximalne 100 znakov" << endl;
while(input.size() > max)
cin >> input;
while (cin >> input)
Convert(input);
}
}else{
cout << "Minimalne 1 a maximalne 100 uloh" << endl;
}
system("pause");
}
Your first if in Convert will always fail on a non-underscore and return. I don't think that's what's intended. Agree with other answer on the while cin loop. The next two whiles should be if's apparently. Step thru this code with a debugger and watch it line by line and see where it fails. You've got multiple issues here, and I'm not entirely sure what the intent is.
Edit - I didn't parse the extra parenthesis correctly. The first if in convert is actually okay.