Skipping of For loop while using goto - c++

This is my code for finding a palindrome of a string.
The initial execution works perfectly.
But when it comes to executing the program again, it goes to the label, and skips the cin statement and directly executes everything and finally reaches the end.
This didn't happen when I used it in c++ 6.0, but happens in visual studio 2015
Thanks in advance for your help.
#include "stdafx.h"
#include<iostream>
using namespace std;
void main()
{
char string[100], ch;
int x, i, j, flag = 0;
label:
cout << "Enter a string. Max Length 99 : ";
cin.getline(string, 100);
x = strlen(string);
cout << "Checking For Palindrome...........";
for (long i = 0; i < 5000000; ++i)
{
cout << "";
}
cout << endl;
for (i = 0, j = x - 1; i < x / 2; ++i, --j)
{
if (string[i] == string[j])
continue;
else
{
flag = 1;
break;
}
}
if (flag == 1)
cout << "The String You Entered Is Not A Palindrome";
else
cout << "The String You Entered Is A Palindrome";
cout << "\nDo you want to execute again? (Y/N)";
cin >> ch;
if (ch == 'y' || ch == 'Y')
goto label;
else
cout << "See You Later :)";
}

Related

I'm trying to check my array list input if its an int or string but this seems to crash and just go into infinite loop

#include <iostream>
#include <stdio.h>
#include <ctype.h>
using namespace std;
class List{
private:
int A[10];
int i;
public:
List(){
i = 0;
}
void insert(){
int v;
for(int j = 0 ; j < 10 ; j++){
cout << "\nElement you want to insert: (" << i+1 << "). ";
cin >> v;
if(i <= 9){
A[i] = v;
i++;
}
else{
cout << "\nWrong Input" << endl;
break;
}
}
if(i > 9){
cout << "\nYour List Capacity is Full.\n" << endl;
}
}
void display(){
cout << "\n{ ";
for(int j = 0 ; j < i ; j++)
cout << A[j] << " ";
cout << "}\n" << endl;
}
void remove(){
int p;
cout << "\nElement you want to remove (0 - 9): ";
cin >> p;
if (i == 0){
cout << "\nList is empty!\n" << endl;
return;
}
if (p >= 0 && p < i){
for(int j = p ; j < i-1 ; j++)
A[j] = A[j + 1];
i--;
}
}
void size(){
cout << "\nYour list size is: " << i << endl;
}
void checkcapacity(){
int arrSize = sizeof(A)/sizeof(A[0]);
cout << "\nThe Capacity of the array is: " << arrSize << endl;
}
};
int main(){
List l;
int a;
cout << "\t\t\t\t\t\tWelcome to List Program!";
while(a != 4){
int choose;
cout << "\nThe Program have following options:\n1. Insert\n2. Display\n3. Remove\n4. Check Size\n5. Check Capacity\n6. Exit\n\nNote: Your list capacity is 10!";
cout << "\n\nChoose (1 - 5): ";
cin >> choose;
if (choose == 1){
l.insert();
}
else if (choose == 2){
l.display();
}
else if (choose == 3){
l.remove();
}
else if (choose == 4){
l.size();
}
else if (choose == 5){
l.checkcapacity();
}
else if (choose == 6){
a = 4;
}
}
cout << "Thank you for using this program!";
}
I'm using this class in my main function in which I call them but when the user inputs a char or string in the insert function it goes into infinte loop. Int i is my counter and it just contains the size of my array list im just trying to put a check of character that if user input a character is should show an error.
Here's one way to write your insert function
void insert()
{
int v;
for(int j = 0 ; j < 10 ; j++)
{
cout << "\nElement you want to insert: (" << i+1 << "). ";
if (cin >> v)
{
if (i < 10)
{
A[i] = v;
i++;
}
}
else
{
cin.clear(); // clear error
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // discard any pending input
}
}
if (i >= 10)
cout << "\nYour List Capacity is Full.\n" << endl;
}
The important part is the recovery from bad input. First cin.clear() is called to clear the stream error state, secondly cin.ignore(...) is called to discard any pending input.
More details here

I have a hangman game I'm making, and I need help figuring out why it's not fully working

I'm making a hangman game in C++ and I am close to finishing, however I have one major issue. I have to get the game to only allow the user 4 guesses, but my program doesn't register the correct number of guesses.
I've tried to change variables as well as the conditions within the if and else statements regarding guessing.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
cout << "Welcome to hangman!" << endl;
char choice = 'y';
while (choice == 'y') {
string word;
cout << "Enter a word to guess: ";
getline(cin, word);
if (word.empty()) {
cout << "The word should not be blank.\n";
continue;
}
bool contain_space = false;
for (char c : word) {
if (isspace(c)) {
contain_space = true;
break;
}
}
if (contain_space) {
cout << "The word cannot contain spaces.\n";
continue;
}
vector <bool> index;
for (int i = 0; i < word.size(); i++) {
index.push_back(false);
}
**int guess_correct = 0;**
int guess_wrong = 4;
char letter;
while (guess_wrong >= 0 && guess_correct < word.size()) {
bool valid_guess = true;
cout << "Guess a letter." << endl;
cin >> letter;
for (int i = 0;i < word.size(); i++) {
if (word[i] == letter) {
valid_guess = true;
index[i] = true;
guess_correct++;
break;
}
else {
guess_wrong = guess_wrong - 1;
}
}
for (int i = 0; i < word.size(); i++) {
if (index[i] == true) {
cout << word[i] << "\t";
}
else {
cout << "___\t";
}
}
cout << endl;
}
cout << "Would you like to play again? (y/n)" << endl;
cin >> choice;
cin.ignore();
}
return 0;
}
The black ticks show the beginning of the code section I'm stuck on. Each time I run it, it will let me go through the game with correct guesses, but incorrect guesses don't allow for 4.
You are decrementing guess_wrong for each letter in the word that doesn't match, not once for the "whole guess".
you probably want to move the guess_wrong = guess_wrong - 1; // aka guess_wrong-- out of the for loop and only do it if (!valid_guess).

C++ a function call is not called again after the loop iterates

Hey so I am relatively a beginner at programming. I am trying to create a very simple minesweeper game over a 2D array, the issue I am running into is after the player steps on a mine (game over) they are given the option to play again. After this the set difficulty function is supposed to be called a second time (since it is within the loop) and a new minefield is to be generate. Unfortunately none of that is happening and the program skips that process.
Here is my code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int choose_difficulty(int x);
int generator();
int main()
{
//create initial variables
string Ans;
int Rounds;
int NewPosition_x = 0;
int NewPosition_y = 0;
//ask user if he wants to run the program and expect input
cout << "Would you like to play a game? Y/N" << endl;
cin >> Ans;
//based on user input the program will run or not
if (Ans == "Y" || "y") {
while (Ans == "Y" || "y")
{
//Create position variables to be checked
int Position_x;
int Position_y;
//ask user how many rounds in the game they want
cout << "How many chances do you want to give yourself?" << endl;
cin >> Rounds;
//Generate minefield could not be done as separate function since you cannot output an array
int a = choose_difficulty(a);
int mines;
int n,m;
srand (time (0));
if(a == 0) {
mines = 3;
n = 4;
m = n;
}
else if (a == 1){
mines = 5;
n = 4;
m = n;
}
else if (a == 2){
mines = 7;
n = 4;
m = n;
}
int minefield[n][m] = { };
int g, h;
for (int num = 0; num < mines; num++) {
g = rand()%n;
h = rand()%n;
minefield[g][h] = 1;
}
for (int x = 0; x < Rounds; x++)
{
//Begin Game
cout << "Where are you at to avoid the mines? (Enter a 2 numbers 0 through 3)" << endl;
cin >> NewPosition_x >> NewPosition_y;
//check if the player has entered a new position
while (NewPosition_x == Position_x && NewPosition_y == Position_y) {
cout << "You have to move somewhere, put a valid location" << endl;
cin >> NewPosition_x >> NewPosition_y;
}
//check to see if that position is valid
while ((NewPosition_x < 0 || NewPosition_x > 3) || (NewPosition_y < 0 || NewPosition_y > 3)) {
cout << "I'm sorry, but that place doesn't exist. Try somewhere else" << endl;
cin >> NewPosition_x >> NewPosition_y;
}
//Assign Player Position and check position vs mines
Position_x = NewPosition_x;
Position_y = NewPosition_y;
if (minefield[Position_y][Position_x] == 1) {
cout << "You stepped on a mine, Game Over" << endl;
cout << "You minefield was this:" << endl;
for (int i=0; i < n; i++){
for (int j=0; j < n; j++){
cout << minefield[i][j] << "\t";
}
cout << endl;
}
cout << "Would you like to play again? Y/N" << endl;
cin >> Ans;
if (Ans == "n" || Ans == "N"){
return 0;
}
}
else if ((minefield[Position_x + 1][Position_y] == 1) || (minefield[Position_x - 1][Position_y] == 1) || (minefield[Position_x][Position_y + 1] == 1) || (minefield[Position_x][Position_y - 1] == 1)) {
cout << "You're hot right now, you better watch your step. Continue to the next round" << endl;
}
else {
cout << "You're safe. Continue to the next round" << endl;
}
}
}
}
return 0;
}
int choose_difficulty(int a)
{
do{
string difficulty;
//Difficulty Selection
cout << "Choose the game difficulty: Easy, Medium, Hard" << endl;
cin >> difficulty;
if (difficulty == "easy" || difficulty == "Easy"){
a = 0;
}
else if (difficulty == "medium" || difficulty == "Medium"){
a = 1;
}
else if (difficulty == "hard" || difficulty == "Hard"){
a = 2;
}
else {
cout << "Invalid input";
a = 3;
}
}while (a == 3);
return a;
}
You should be careful on this kind of error:
//based on user input the program will run or not
if (Ans == "Y" || "y") {
while (Ans == "Y" || "y")
{
This, above, will always be true being "y" different from 0 (false).
Instead you need to check that Ans is either equal to "Y" or "y" in this way:
//based on user input the program will run or not
if (Ans == "Y" || Ans == "y") {
while (Ans == "Y" || Ans == "y")
{
Or use, as suggested in the comments, std::toupper()
UPDATE
It seems you have a problem on your buffer you should use cin.ignore() in order to clean it;

Why do i get a segmentation fault when I try to enter "x" to exit my program

the function DataDisplayAndSearch for some reason causes a segmentation fault when i enter "x" to exit the program. I have tried debugging and cannot figure out what the problem could be. This is homework
string DataDisplayAndSearch (int customerCount, string ssn[])
{
//local variables
int index;
int count;
int numberLen;
int numberLocation = NOT_FOUND;
int high;
int low;
int middle;
bool invalidNumber = false;
string choice;
cout << " Social Security Numbers on file are:" << endl;
for (index = 0; index < customerCount; index++)
{
cout << " " << ssn[index] << " ";
}
do
{
cout << endl << endl << " Enter SSN to find (or X to exit):";
invalidNumber = false;
cin >> choice;
if (choice != EXIT && choice != EXIT1)
{
numberLen = choice.length();
if (numberLen < LENGTH || numberLen > LENGTH)
{
invalidNumber = true;
}
for (count = 0; count < LENGTH; count++)
{
if (isprint(choice[count]));
else
{
invalidNumber = true;
}
}
if (choice[IDX2] != DASH || choice[IDX5] != DASH)
{
invalidNumber = true;
}
low = 0;
high = customerCount - 1;
while ((low <= high) && (numberLocation == NOT_FOUND))
{
middle = (low + high) / 2;
if (choice > ssn[middle])
{
high = middle - 1;
}
else if (choice < ssn[middle])
{
low = middle + 1;
}
else
{
numberLocation = middle;
}
}
if (numberLocation == NOT_FOUND)
{
cout << " Error!! Please enter a valid SSN." << endl;
}
if (invalidNumber)
{
cout << " Input dashes and digits " << choice << " are formatted."
<< " SSN must be exactly 11 characters long, formatted as:"
<< " ###-##-###" << endl;
}
} //end of if
} while (((invalidNumber) && (choice != EXIT && choice != EXIT1 ) && (numberLocation == NOT_FOUND)));
}
When the outer loop exits for any reason, including choice == EXIT, the function exits without providing a return value of type string. The caller then attempts to use a non-existent string object, hence the crash.
Crossing the closing brace of a function with a non-void return type is undefined behavior. It may crash, but might not crash every time. Your compiler might warn you about things like this if you can enable its warning feature, such as by -Wall on the command line.

Strange first element of array after reading in from file

I'm reading in a sodoku board from a text file. The board is represented by 9 rows of 9 digit numbers, like this:
594632817
123478569
678159234
215346798
346897125
789215346
437561982
851924673
962783451
EDIT
Here are the results when I change the while condition to (input >> char):
Output as chars are read in:
96212486
71931369
48728254
35185947
67350
Output of printArray:
962124867
193136948
728254351
859476735
�$%w��
����QȿȔ
L�`g�Pw
���w�
And here's the output for while (!input.eof()):
�94632817
123478569
678159234
215346798
346897125
789215346
437561982
851924673
962783451
END EDIT
The trouble is, when I place each digit into a multidimensional array, the element at [0][0] appears as a shaded question mark (compiled with g++). The problem only surfaces when I'm printing out the contents of the array, the data as it's read in appears to be fine. For what it's work, this also happens if I cout << board[0][0] from the main function.
Any help would be appreciated!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int createArray(string filename);
bool checkRows(char board[][9]);
bool checkColumns(char board[][9]);
bool checkBoxes(char board[][9]);
void printArray(char board[][9]);
int main ()
{
char board [9][9];
int i = 0;
int j = 0;
int count = 0;
ifstream input("board.txt");
char ch;
while (input >> ch)
{
// ch = input.get();
if (ch != '\n')
{
cout << ch;
board[i][j] = ch;
j++;
if (j % 9 == 0)
{
i++;
}
}
if (j > 8)
j = 0;
if (i > 8)
i = 0;
count++;
if (count % 10 == 0)
cout << endl;
}
input.close();
printArray(board);
cout << checkRows(board) << endl;
cout << checkColumns(board) << endl;
return 0;
}
void printArray(char board[][9])
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
cout << board[i][j];
}
cout << endl;
}
cout << board[0][0] << endl;
cout << board[0][1] << endl;
}
By doing this, reading ch two times.
Remove ch = input.get(); and you will read each number correctly.
while (input >> ch)
{
ch = input.get();
...
}
Again, consider changing condition below to make sure correct endl placement
if (count % 10 == 0)
cout << endl;
to
if (count % 9 == 0)
cout << endl;