C++ variable/looping issue [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
No idea where the issue is coming from so I will insert the whole sub-routine.
When you insert a string into the guess space it will loop infinitly, if you insert a number it will return "ion do you want to go?"(which isn't even written anywhere in the program).
void guess(){
int guess;
string guess2;
string guess_status="";
bool win;
int attempts;
int counter;
int num;
while (guess2 != "exit"){
num=rand() %100 + 1;
win=0;
counter=0;
while (win != 1){
attempts=5-counter;
cout << "Guess a number Attempts Left: " << attempts << endl;
cout << "between 1 and 100 ============================\n The Guesing Game\n ============================" << endl;
cout << "\n" << guess_status << endl;
cout << "\nGuess: ";
cin >> guess;
system("cls");
if (!cin) {
guess2=guess;
if (guess2 != "exit"){
guess_status="Please insert a valid number, restarted game.";
win=1;
}
}
if (cin){
if (guess==num){
win=1;
guess_status="Correct! Generated new number.";
}
if (guess != num){
if (guess < num){
guess_status=num +"was too low!";
}
if (guess > num){
guess_status=num +"was too high!";
}
}
}
}
}
}
The routine is indented, it just didn't paste that way

int guess;
string guess2;
guess2=guess;
This is your problem. You can't convert an int into a string this way. What you're actually doing is telling the computer that guess2 is a string that starts at the memory address that the value of guess is currently. That's why you're getting a string output that's not even in your program- it's just what happens to be at that address.
See here for how to convert an int to a string:
Easiest way to convert int to string in C++
Also, don't use cin >> guess. Get the input as a string, then check to see if it can be converted to an integer.

Related

Handling invalid user inputs in C++ [duplicate]

This question already has answers here:
cin input (input is an int) when I input a letter, instead of printing back incorrect once, it prints correct once then inc for the rest of the loop
(2 answers)
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 4 years ago.
I've been coding in C++ for all of a few days, so please talk to me like I'm a baby. With that out of the way,
I've made a short algorithm that asks a set of questions (to be answered 0 for no and 1 for yes) and stores the user's answer as an integer. Everything works as expected as long as the user only inputs integers (or, in one case, a string with no spaces).
But if the input doesn't match the variable type, the program immediately outputs this infinite loop that appears later in the program. That loop is supposed to print a question, wait for input, and then ask again if the answer isn't '1', but in the failure state it just prints the question without end. I can't see any reason why the previous questions would be connected to this. It doesn't happen on the questions that come after it, if that's a clue.
Here's a pared-down version of my code with, I hope, all the important information intact:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int answer1;
string answer1C;
int answer2;
int answer2B;
int score;
score = 0;
cout << "Question 1" << endl;
cin >> answer1;
if (answer1 == 1)
{
++score;
//some other questions go here
cout << "Question 1C" << endl;
cin >> answer1C;
if (answer1C.size() == 6)
{
++score;
}
}
cout << "Question 2" << endl;
cin >> answer2;
if (answer2 == 0)
{
cout << "Question 2B" << endl;
cin >> answer2B;
if (answer2B == 0)
{
--score;
}
while (answer2B != 1) //Here is the infinite loop.
{
cout << "Question 2B" << endl;
cin >> answer2B;
}
}
cout << "Question 3" << endl;
//and so on
return 0;
}
I would love to have it accept any input and only perform the ensuing steps if it happens to meet the specified conditions: for instance, in question 1.2, it only awards a point if the answer is a string of length 6, and otherwise does nothing; or in question 2.1, it repeats the question for any input that isn't '1', and moves on if it is.
But in any case whatsoever, I need it to do something else when it fails. Please help me figure out why this is happening. Thank you.

C++ Need help getting an integer from the user and making sure it is between 2 other integers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am new to c++ and cant seem to figure out how to simply get an integer from the user and make sure it is between 0-15. Here is my code so far:
When I run the code it only prints Hello world
int main()
{
int greetAndGet();
cout << "Hello";
return 0;
}
int greetAndGet()
{
int i;
cout << "\nPlease give an integer in [1,15]" << endl;
cin >> i;
cout << endl;
}
int greetAndGet(); is a forward declaration of a function, not a call.
Write greetAndGet(); instead.
Note further that a function should be defined/declared before any call to it. So either place the function definition before main, or write
int greetAndGet(); // forward declaration
int main()
{
greetAndGet();
cout << "Hello";
return 0;
}
...
As pointed out in another answer, int greetAndGet() is a forward declaration that you probably intended to be a call; though you do want to forward declare it before main. As for testing the range of the entered value, you could use a loop to check if it is in the range. I think what you want is this:
int greetAndGet();
int main()
{
int num = greetAndGet();
cout << "Hello";
return 0;
}
int greetAndGet()
{
int i;
cout << "\nPlease give an integer in [1,15]" << endl;
do {
cin >> i;
if(i < 1 || i > 15)
{
cout << "Number not in [1,15], please try again" << endl;
}
} while(i < 1 || i > 15);
cout << endl;
return i;
}
I'm not sure what you want to do with the number, but this should get you the entered number.

cout won't print in function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm pretty new to programming so this might be a question with an obvious answer for you guys and I'm really stumped, why doesn't cout work in the following function? I've included the iostream header so I'm assuming it has something to do with it being in the function?
int inputFileData(song musicLibrary[])
{
char discard = ' ';
int counter = 0, length = 0;
ifstream inData;
inData.open("songs.txt");
if (!inData)
{
cout << "Error: No input file found " << endl;
cout << "Program terminating..." << endl;
return 1;
}
while (!inData.eof())
{
inData.getline(musicLibrary[counter].title, ARRAY_CONST, ';');
inData.getline(musicLibrary[counter].artist, ARRAY_CONST, ';');
inData >> musicLibrary[counter].durationMinutes;
inData.get(discard);
inData >> musicLibrary[counter].durationSeconds;
inData.get(discard);
inData.getline(musicLibrary[counter].album, ARRAY_CONST, '\n');
length = strlen(musicLibrary[counter].album);
if (length = 0)
{
cout << length << endl; //This cout object doesn't work in this function
break;
}
else
counter++;
}
return counter;
}
The line if (length = 0) should be if (length == 0).
Elaborating Eli's answer:
if (length = 0)
Assigns the value 0 to length and then evaluates the expression. Since the expression returns 0 the condition evaluates to false and you don't enter the if clause.
Instead, use if (length == 0)

Element counting issue [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
#include <iostream>
using namespace std;
int countLetters(char text[], char letter);
int main()
{
char letter;
cout << "Enter a letter: ";
cin >> letter;
cin.ignore();
char text[1024];
cout << "Enter text: ";
cin.getline(text, 1024);
int letterCount = countLetters(text, letter);
cout << "Number of '" << letter << "'s: " << letterCount << endl;
return 0;
}
int countLetters(char text[], char letter)
{
int letterCount = 0;
for (int i = 0; i <= text[i]; i++)
{
if (letter == text[i])
letterCount++;
}
return letterCount;
}
This code, as written, is designed to ask the user for, first, the letter they want to search for in a line of text. Second, it will ask the user to input the line of text they want to have searched. Finally, it will spit out how many letters there are in the specific line of text they input.
My specific error lies here: when user asks for 'e' in "CS 124 - Introduction to Software Development", program only declares that there is one 'e' . I'm unsure what's wrong, because when you run the program and input 'o' while asking to search the exact same line of text, you get the proper number of 'o' values returned, 4.
Any ideas as to what my error is and why it glitches when searching for 'e' ?
Your for condition is wrong, the for loop should continue while i is less than text's length not the value of text[i]. Since this is C++ you should use strings not character arrays, why make it harder on yourself?
The code below is a C++ approach, note that my C++ is a bit rusty and the code might contain errors.
#include <iostream>
#include <string>
using namespace std;
int countLetters(string text, char letter);
int main() {
char letter = ' ';
string text;
cout << "Enter a letter: ";
cin >> letter;
cin.ignore();
cout << "Enter text: ";
getline(cin, text); // use 'getline(cin, text)' instead of 'cin >> text'
int letterCount = countLetters(text, letter);
cout << "Number of '" << letter << "'s: " << letterCount << endl;
return 0;
}
int countLetters(string text, char letter) {
int letterCount = 0;
for (int i = 0; i < text.size(); i++) {
if (letter == text[i]) {
letterCount += 1;
}
}
return letterCount;
}
change the condction
i <= text[i]
to
text[i] != '\0'

Why does the loop loop itself when "else" is triggered? Is this because of things called memory allocation? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm just a beginner and trying out some code that my teacher taught us to use and things from the textbook.
This program is designed to be for the user to enter in their name and enter in the password as what the system asks them to put down.
Can somebody explain to me why this loop keeps looping itself infinitely when else is triggered?
Also, what does the cin.ignore do to the memory of the char name? Why is 80 better than 20?
AND, why aren't the random numbers actually random? Every time I run it, the numbers are the same.
Thank you all so much!
#include <iostream>
#include <cstdlib>
using namespace std;
int main ()
{
char name[20];
int pwd, rand1, rand2;
for (int i=0;i<1; i++)
{
cout<<"Name: ";
cin.get(name, 20);
cin.ignore(80, '\n');
cout<<endl;
srand(rand() % 1000);
rand1 = (rand() % 21);
rand2 = (rand()%6);
cout<<"Password: "<<rand1<<"*"<<rand2<<"= ";
cin>>pwd;
if(pwd == rand1*rand2)
{
cout<<endl<<"Welcome to our main page, "<<name<<"."<<endl;
}
else
{
cout<<"Wrong password, type again." <<endl;
i--;
}
}
return 0;
}
First up formatting of code will help you understand better.
Also avoid using namespace std, its bad practice and clutters the global scope with names. Instead use using std::xxxx if you dont want to write std::cout, std::cin, etc every time.
Reformatted code:
#include <iostream>
#include <cstdlib>
using std::cin;
using std::cout;
using std::endl;
int main ()
{
char name[20];
int pwd, rand1, rand2;
for (int i = 0; i < 1; i++) {
cout << "Name: ";
cin.get(name, 20);
cin.ignore();
cout << endl;
srand(rand() % 1000);
rand1 = (rand() % 21);
rand2 = (rand() % 6);
cout << "Password: " << rand1 << "*" << rand2 << "= ";
cin >> pwd;
cin.ignore();
if(pwd == rand1*rand2) {
cout << endl << "Welcome to our main page, " << name << "." << endl;
} else {
cout << "Wrong password, type again." << endl;
i--;
}
}
return 0;
}
Secondly as you can see in the above code the line cin.ignore(); has been added after cin >> pwd. Before your code was getting cin >> name, leaving '\n' in the input, ignoring '\n', getting cin >> pwd, leaving '\n' in input, looping and reading input as empty with a '\n', leaving another '\n' in input, first '\n' is removed by ci.ignore(), second '\n' read by cin >> pwd, ... etc. Or at least this is how I understand it.
Somebody has answered the first question:Because when you i--, the i in the for loop keeps decreasing and then increasing.-By Gasim
Then, if your input is longer than 20, the program may stop. So you need cin.ignore(80, '\n') to ignore the excess input. The number 80 is just a big number. You can replace it with another number-only if it's big enough.
You are supposed to use srand with time. srand(time(null)) may help.