Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to figure out whether a pre or post test loop would be the best method so that the user can continue to input values that will be searched for, until a sentinel value is entered to end the program. Also, what would my parameters look like for the loop? Here is my code, I need to include the loop. Also, I understand that a post test loop is executed at least once. Thanks in advance!
#include<iostream>
using namespace std;
int searchList( int[], int, int); // function prototype
const int SIZE = 8;
int main()
{
int nums[SIZE]={3, 6, -19, 5, 5, 0, -2, 99};
int found;
int num;
// The loop would be here
cout << "Enter a number to search for:" << endl;
cin >> num;
found = searchList(nums, SIZE, num);
if (found == -1)
cout << "The number " << num
<< " was not found in the list" << endl;
else
cout << "The number " << num <<" is in the " << found + 1
<< " position of the list" << endl;
return 0;
}
int searchList( int List[], int numElems, int value)
{
for (int count = 0;count <= numElems; count++)
{
if (List[count] == value)
// each array entry is checked to see if it contains
// the desired value.
return count;
// if the desired value is found, the array subscript
// count is returned to indicate the location in the array
}
return -1; // if the value is not found, -1 is returned
}
Your question is more of a use case dependent.
Post Case: When you need the loop to run AT LEAST once ( 1 or more times)
Pre Case: The loop can run 0 or more times.
I must say, I'm not entirely sure what you want to know. I would honestly recommend a good book on C++. Post test loops are not super popular in C++ (they are of the form "do.. while" where "while" loops / pre test loops are much more common). A little more information is available here: "Play It Again Sam"
EDIT: you need to get data from the user, test it, and then do stuff based on it. Your best bet is something along the lines of
static const int SENTINEL = ??;
int num;
cout << "please input a number" << endl;
cin >> num;
while( num != SENTINEL ) {
// DO STUFF HERE
// Now get the next number
cout << "please input a number" << endl;
cin >> num;
}
Related
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.
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.
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
The goal of this code is to pass an array through a function (which I'm already having a difficult time understanding). I went through with a pen and paper and traced the code and I think I just don't know enough to understand what's going wrong. All the test scores I throw in just push back a ridiculously large negative number. I'm not asking for you guys to do my homework because I really want to try and understand what I'm doing, but any help would really be appreciated right now.
#include <iostream>
//function prototype
double average(int studentScores[], int size);
double studentScores[4];
bool runAgain(void);
int main() {
do {
int studentScores[4], size = 4, result;
string score;
cout << "This program will calculate the average of four diffrent exam scores." << endl;
for (int i = 0; i < size; i++) {
studentScores[i] = 0;
cout << "Please Enter Exam Score " << i + 1 << ": ";
getline(cin, score);
}
for (int i = 0; i < size; i++) {
result = (studentScores[1] + studentScores[2] + studentScores[3] + studentScores[4]) / size;
studentScores[i]++;
}
cout << "The Average Exam score is " << result << endl;
} while (runAgain());
system("pause");
return 0;
}
//function implementation
double average(int studentScores[], int size) {
for (int i = 0; i < size; i++) {
return (studentScores[i]++ / size);
}
}
bool runAgain(void) {
char userResponse;
cout << "\nWould you like to run again (y or n): ";
cin >> userResponse;
if (userResponse == 'y' || userResponse == 'Y')
return(true);
return(false);
}
First obvious bug:
int studentScores[4]
studentScores has 4 elements, numbered studentScores[0] through studentScores[3].
But your code accesses studentScores[4] in
result = (... + studentScores[4]) / ...
which doesn't exist (and doesn't access studentScores[0], which does).
Glad to try to help ya out without giving you the answer.
I'm gonna sprinkle some questions throughout your code that you should be asking yourself in future programs whenever you get unexpected output.
#include <iostream>
//function prototype
double average(int studentScores[], int size);
double studentScores[4];
bool runAgain(void);
int main() {
do {
int studentScores[4], size = 4, result;
string score;
/* Above, you declared a string to store the user's input in.
In C++, the string "4" DOES NOT equal the integer 4.
How will you handle the fact that the variable 'score' is of type
string, but you want to work with integers?
Is there an easy way to get rid of this issue? (hint: use cin)
*/
cout << "This program will calculate the average of four diffrent exam scores." << endl;
/* In the below for-loop, think about what the value of 'score' will be
after each iteration. (Hint, getline replaces the existing value of score).
Also, where is the code that saves the user's inputted numbers to an array?
Learn how to write values to an array http://www.cplusplus.com/doc/tutorial/arrays/
*/
for (int i = 0; i < size; i++) {
studentScores[i] = 0;
cout << "Please Enter Exam Score " << i + 1 << ": ";
getline(cin, score);
}
/* In the for-loop below, you already noticed that your array has random
values in it. The comment about the above for-loop should address that issue.
Equally important though is understanding what the heck is happening in this
loop below. After you fix the bug in the for-loop above (which will
get the values in the array to equal the user's inputs), you'll be faced
with issues in this loop below.
My advice is to understand what happens when the program
executes "studentScores[i]++". First, it gets the number in the array at
the ith+1 position, then it increments that number by 1. Cool, but what
are you doing with the result of that? It's not being put to use anywhere.
Also, note that because the array is never being updated,
the line above it just calculates the same number and stores it in 'result'
every iteration of the loop.
*/
for (int i = 0; i < size; i++) {
result = (studentScores[1] + studentScores[2] + studentScores[3] + studentScores[4]) / size;
studentScores[i]++;
}
cout << "The Average Exam score is " << result << endl;
} while (runAgain());
system("pause");
return 0;
}
// this function doesn't seem to be used, but understanding what
// is wrong with it will help you understand how to code.
// First, note that once a function hits 'return', it will
// never execute any more code in that function.
// So here, your return statement in the for-loop will prevent an
// actual loop from occuring (since the function will exit as soon as the first loop iteration is entered)
// Second, note that you are just getting the value in the array and adding 1 to it
// before dividing it by 'size', which is not the formula for an average.
double average(int studentScores[], int size) {
for (int i = 0; i < size; i++) {
return (studentScores[i]++ / size);
}
}
bool runAgain(void) {
char userResponse;
cout << "\nWould you like to run again (y or n): ";
cin >> userResponse;
if (userResponse == 'y' || userResponse == 'Y')
return(true);
return(false);
}
I hope these comments helped :) Keep at it!
Don't forget that arrays start at index 0. Trying to access studentScores[4]
will give you an unexpected number.
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
I need help on something. The textbook I am reading that teaches c++ does not do a good job at teaching students the linear searching algorithm. As a result I have tried recreating the algorithm without using any functions. The problem is, the code I have written seems to have some bugs. Just to note I am using the Microsoft Visual Studios 2013 IDE. As a result, can anyone please tell me what is wrong with my code? Here is the algorithm I have written in English. The Algorithm will not show the variable and array definitions but the source code will.
P.S. This is not a homework assignment. It is just for fun :)
P.S. For some reason the code formatting was very glitchy.
Algorithm:
Ask the user to enter a number
Create a for loop
Inside the for loop traverse through each element in the array and compare
it with the number the user inputted
If the element in the array is EQUAL to the number the user inputted, display a message saying it was found
If the element in the array is NOT EQUAL to the number the user inputted, display a message saying it WASN'T found.
code:
#include <iostream>
using namespace std;
int main()
{
// Create the array
int array[6] = {1,2,3,4,5,6};
int number;
// Ask the user to enter a number
cout << "Enter a number: ";
cin >> number;
// Create a for loop to traverse through each number in the array
//to see if it equals the user inputted number
for (int i = 0; i < 6; i++)
{
if (number == array[i])
{
cout << "Number Found: " << array[i] << endl;
}
else if (number != array[i])
{
cout << "Number Not Found!" << endl;
}
}
return 0;
}
The output if I entered 3 would be the following:
Number Not Found!
Number Not Found!
Number Found: 3
Number Not Found!
Number Not Found!
Number Not Found!
your logic output decision for each iteration. But it seems you've to output your decision only once.
So, for this reason declare a boolean variable globally and set false as a value of this value.
For each iteration check it is found. if found then set the boolean value to TRUE.
for Final output check global boolean value either true or false and print output
Remove the cout from inside the loop. Use a flag, ie if the number is found, set it to true and then write the print statement outside using an if.
int flag=0;
for(int i=0;i<6;i++){
if(number==arr[i])
flag=i+1;
}
if(flag) cout<<"found at position"<<flag;
else cout<<"Not found";
PS: Buy a better textbook
Easier and more fun:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int number;
vector<int> nums{1,2,3,4,5,6};
cout << "Find a number: ";
cin >> number;
for_each(cbegin(nums), cend(nums),
[&](const int& x)
{
if(x == number)
cout << "found " << x << endl;
else
cout << "could not find " << endl;
});
}
But a good starting point for linear search would be:
template<typename I, typename T>
I find (I first, I last, const T& val)
{
while (first != last) {
if (*first == val) return first;
++first;
}
return last;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a hangman program, but I'm having issues with randomly choosing a word out of the list...
I get the errors:
-error C2661: 'rand' : no overloaded function takes 1 arguments
-IntelliSense: too many arguments in function call
They are both referring to the rand function noted in the code where I'm trying to randomly choose a word out of the array so the user can guess.
// Hang.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
using namespace std;
const int MAXLENGTH=80;
const int MAX_TRIES=5;
const int MAXROW=7;
int letterFill (char, char[], char[]);
void initUnknown (char[], char[]);
int main ()
{
char unknown [MAXLENGTH];
char letter;
int num_of_wrong_guesses=0;
char word[MAXLENGTH];
char words[][MAXLENGTH] =
{
"india",
"america",
"germany",
"china",
"canada"
};
//THIS IS WHERE THE ISSUE IS OCCURRING vvvvvvv
//choose and copy a word from array of words randomly
rand();
int n=rand(5);
strcpy(word,words[n]);
// Initialize the secret word with the * character.
initUnknown(word, unknown);
// welcome the user
cout << "\n\nWelcome to Hangman!";
cout << "\n\nYou have " << MAX_TRIES << " tries to try and guess the word.";
cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
// Loop until the guesses are used up
while (num_of_wrong_guesses < MAX_TRIES)
{
cout << "\n\n" << unknown;
cout << "\n\nGuess a letter: ";
cin >> letter;
// Fill secret word with letter if the guess is correct,
// otherwise increment the number of wrong guesses.
if (letterFill(letter, word, unknown)==0)
{
cout << endl << "Sorry, that letter was wrong." << endl;
num_of_wrong_guesses++;
}
else
{
cout << endl << "You found a letter!" << endl;
}
// Tell user how many guesses has left.
cout << "You have " << MAX_TRIES - num_of_wrong_guesses;
cout << " guesses left." << endl;
// Check if they guessed the word.
if (strcmp(word, unknown) == 0)
{
cout << word << endl;
cout << "You guessed it!";
break;
}
}
if(num_of_wrong_guesses == MAX_TRIES)
{
cout << "\nSorry, you lose...you've been hanged." << endl;
cout << "The word was : " << word << endl;
}
getch();
return 0;
}
/* Take a one character guess and the secret word, and fill in the
unfinished guessword. Returns number of characters matched.
Also, returns zero if the character is already guessed. */
int letterFill (char guess, char secretword[], char guessword[])
{
int i;
int matches=0;
for (i = 0; secretword[i]!='\0'; i++)
{
// Did we already match this letter in a previous guess?
if (guess == guessword[i])
return 0;
// Is the guess in the secret word?
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
// Initialize the unknown word
void initUnknown (char word[], char unknown[])
{
int i;
int length = strlen(word);
for (i = 0; i < length; i++)
unknown[i]='*';
unknown[i]='\0';
}
// end
rand takes no argument
You probably want :
int n=rand() % 5;
std::rand() generates a pseudo random number, if you want a number 0, 1, 2 3 or 4, which i guess you are trying to do use the following:
int n = rand()%5;
This generates a random number and then the % gives the rest value if you would divide by 5. If the random number is 12, you can 'put two fives in it', and the rest value will be 2.
One thing to note is that in C++ using rand() is generally a bad idea, because it will not give you a truly random number, and using % makes it worse, but I think you will be fine since this is just a small program.
Watch this talk if you want to know how to properly generate a random number in c++