I'm trying to have a user enter a number, and then have double check that they haven't already entered that particular number. I thought storing the user entered number in an array using one counter and then checking that same array with a for loop controlled counter would do the trick, but when I use the for loop counter in the array elements, it seems to always be zero. Can someone point me in the right direction here? I can't figure out what I'm doing wrong.
#include <iostream>
using namespace std;
int main() {
int guess[101] = { 0 };
int count = 0;
int check = 0;
while (guess[count] != 1) {
count++;
cout << "Enter an integer." << endl;
cin >> guess[count];
if (guess[count] == 0) {
return 0;
}
for (check = 0; check < count; check++) {
cout << guess[check] << endl;
if (guess[count] = guess[check]) {
cout << "You already guessed " << guess[check] << ". Try a different integer between 1 and 100.\n" << endl;
}
}
}
}
if (guess[count] == guess[check]) double equal to should be used for comparison.
Related
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main() {
int arr[6]={1,8,24,43,15,20};
int input;
bool exists = find(begin(arr), end(arr), input) != end(arr);
cout << "Enter a number : " << endl;
cin >> input;
if (input==1) {
cout << "It is indeed in the array." << endl;
}
else {
cout << "Nope, try again." << endl;
}
}
I want to find a way to make it more specific where a user can input a number and it will be able to find which slot of the array it is in. For example:
int arr[5]={1,2,3,4,5}; User inputs: 4,. Value 4 is in slot 4. Anyone got any ideas?
std::find returns iterator to the element (if found). Instead of simply comparing it with end, you can use that iterator to get the index. Index of an element in a range is same as the distance of the element from the beginning of the range. As such, simply calculate the distance from begin to the found iterator. There is a standard function to calculate that distance. Its name is std::distance.
Note that indices in C++ language (and in most programming in general) are 0 based, so you need to add 1 to the index to get the corresponding "slot" as you've specified.
P.S. As Thomas Matthews points out, your example program is broken. You should fix that before attempting to calculate the slot.
You can do it by using a linear search also!
#include <iostream>
using namespace std;
int main() {
int arr[6]={1,8,24,43,15,20};
int input, slot = -1;
cout << "Enter a number : " << endl;
cin>>input;
bool flag = false;
for(int i = 0; i < 6; i++){
if(input == arr[i]){
slot = i + 1;
flag = true;
break;
}
}
if(flag){
cout << "It is indeed in the array. Slot: " << slot << endl;
}else{
cout << "Nope, try again." << endl;
}
return 0;
}
Use std::find to get an iterator to target item and then use std::distance to compute its zero-based index! and resolve yours errors! call std::find after cin and add proper return to main!
Try
using namespace std;
int main()
{
int arr[6] = { 1,8,24,43,15,20 };
int input;
cout << "Enter a number : " << endl;
cin >> input;
auto iter = find(begin(arr), end(arr), input);
if (iter != end(arr))
{
cout << "Slot is ." << distance(begin(arr), iter) + 1 << endl;
}
else
{
cout << "Nope, try again." << endl;
}
return 0;
}
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;
}
So I am making a program that will create a square based on the users desired size. My code so far reads the value, prints out the top of the square but i'm getting caught up on how to set up the sides because of a nested loop I've created. The issue here is that I need for the loop to reset it's values every time it exists.
Here's my code so far:
#include <iostream>
using namespace std;
int main(int,char**) {
int x;
int z=1;
int l=0;
int n=0;
int q=1;
int m=0;
int o=0;
do{
cout << "Enter length between 0 and 64 (-1 to exit): ";
cin >> x;
if (x>-1&&x<64){
cout << "+";
for (;x-2!=n;++n){
cout << "-";
}
cout << "+" << endl;
}
else{
cout << "Length must be between 0 and 64 inclusive, or enter -1 to exit.";
}
do {
cout << "|";
do {
//cout << " ";
//++m;
//}while (x-2!=m);
cout << "|" << endl;
++o;
}
while (x-2!=o);
++z;
}
while (z!=5);
}
The commented out portion is where the program is getting caught up at, it seems that when I increment m until it exits the do while loop, it holds onto the value that it was incremented to. I know that a continue statement breaks from the loop and begins a new iteration of the loop but it doesn't seem to want to fit inside the do-while loop even if i create an if statement such as
if (x-2==m){
continue;
}
Any help would be appreciated
Just put m = 0; before the loop.
m = 0;
do {
cout << ' ';
++m;
} while (x-2 != m);
Or use a for loop instead;
for (int m = 0; m != x-2; m++) {
cout << ' ';
}
This is the more common idiom for repeating something a certain number of times, since you can see all the conditions related to the loop in a single place.
I have to solve a task so it prints the min, the max and the mode of a set of strings. First I store the strings in a vector, than I sort them and then I print the first and the last of the elements of the vector, which is fine. But I have hard times finding the mode of them. Here is the code I wrote.
#include<stdafx.h>
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
vector<string>words;
cout << "Please enter some words. When finished, just enter 'stop'.\n";
string ant;
int count = 0;
int max = 0;
while (cin >> ant) {
if (ant != "stop") {
words.push_back(ant);
}
else
break;
}
sort(words.begin(), words.end());
cout << "The min of the entered words is " << words[0] << "\n";
cout << "The max of the entered words is " << words.back() << "\n";
}
So far this is good. It does the job as I want. But the problem comes when I have to find the mode of the strings. I found some code on the net for finding mode of given integers and it works for integers. I tried to modify it for strings but I could not get it to work. Here is the code:
for (string test = 0; test<words.size(); ++test) {
if (words[test] == words[test + 1]) {
count++;
}
else if (words[test] != words[test + 1]) {
if (count>max) {
max = count;
mode = words[test];
}
count = 0;
}
}
This gives me a lot of errors, I do not know where to begin. I think the problem is that this is not a proper way to make iteration of strings. I found some explanations about iteration of strings, but its so confusing for me. Any help will be appreciated.
Your modified version of the algorithm that finds the mode of the entered words is correct. The only thing i can say about it is, count and max are keywords in C++ so you'd have to change the names to avoid undesired effects. Also, don't forget to declare mode as type string.
With little modification of your code, this works;
#include<iostream>
#include<vector>
#include <map>
#include<string>
#include<algorithm>
using namespace std;
int main() {
vector<string>words;
cout << "Please enter some words. When finished, just enter 'stop'.\n";
string ant;
int count = 0;
int max = 0;
while (cin >> ant) {
if (ant != "stop") {
words.push_back(ant);
}
else
break;
}
sort(words.begin(), words.end());
cout << "The min of the entered words is " << words[0] << "\n";
cout << "The max of the entered words is " << words.back() << "\n";
//Finding the mode of the entered words
int _count = 0;
int _max = 0;
string mode;
for (unsigned int test = 0, j = 1; test<words.size(); test++, j++) {
if (words[test] == words[j]) {
_count++;
}
else if (words[test] != words[j]) {
if (_count>_max) {
_max = _count;
mode = words[test];
}
_count = 0;
}
}
cout << "The mode of the entered words is " << mode;
}
void offer_help();
bool play_one_game();
int main() {
offer_help();
play_one_game();
}
void offer_help() {
int help_response;
cout << "Need help? (0/1) ";
cin >> help_response;
if (help_response == 1)
cout << "I will generate a pattern of 4 numbers, each in the range 0 through 9.\n Each guess that you enter will be a line containing 4 integers,\n separated by spaces, such as:\n\t 2 4 7 1\n FOr each guess, I will echo back a lost consisting of\n 0's and 1's, with a 1 in a given position meaning that\n you guessed the number, and a zero meaning that you didn't.\n For example, if the actual solution was 2 3 6 1, I'll respond\n\t 1 0 0 1\n See how many guesses it takes you to get the solution!\n\n If you want to give up, type a negative number for one of\n your guesses, and we'll tell you what the pattern was.\n\n";
}
bool play_one_game() {
srand(time(0)); //needed to start randint
vector<int> solution; //vector of 4 randomly generated
//solutions
vector<int> guess; //vector containing user guesses.
vector<int> result;
int guess_input;
for(int i = 0; i < solution.size(); ++i)
solution[i] = randint(10);
int trial_number = 0; //int that shows what guess the user is on
while (play_one_game() == true) {
//ask user for inputs.
cout << "Guess #" << ++trial_number << "? ";
for (int i = 0; i < guess.size(); ++i){
cin >> guess_input;
guess.push_back(guess_input);
}
//outputs error if user inputs a letter.
if (!cin) {
cerr << "Bad input data! Feed me numbers!\n";
return 43;
}
if (cin < 0){
cout << "Too bad! Solution was " << endl;
for(int i = 0; i < result.size(); i++)
cout << (result[i]);
}
//determines if user correctly guessed any of the
//numbers and tells the user which is correct.
for (int i = 0; i < result.size(); i++) {
if (guess[i]==solution[i])
cout << 1 << " ";
else if (guess[i]!=solution[i])
cout << 0 << " ";
}
cout << endl;
// playagain();
cout << endl << "Play again (0/1)? ";
int replay;
cin >> replay;
if (replay == 0) {
play_one_game() == false;
return 5;
}
else if (replay == 1)
play_one_game() == true;
else {
cerr << "wat?\n";
return 10;
}
}
}
This is designed to allow a player to guess a pattern of random numbers.
No idea why I am getting a segmentation fault. The program is supposed to call the offer_help function, then the play_one_game function within main function. Then it should ask the player whether he wants to play again. If no, then bool play_one_game should be set to false and it should exit.
This is related to the play_one_game bool function.
You're getting a segmentation fault, because you end up in an endless recursion in the following line:
while (play_one_game() == true) {
play_one_game will call play_one_game in this line, and this will call play_one_game in the same line again. This will result in a stack overflow at last.
Better use some bool keepPlaying; and while(keepPlaying) instead.
EDIT: Well, this is a little bit more than a simple answer, but I like games, so... have a look at the following code:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
bool play_one_game();
void offer_help() {
int help_response;
std::cout << "Need help? (0/1) ";
std::cin >> help_response;
if (help_response == 1)
std::cout << "I will generate a pattern of 4 numbers, each in the range 0 through 9.\n"
"Each guess that you enter will be a line containing 4 integers,\n"
"separated by spaces, such as:\n"
"\t 2 4 7 1\n"
"For each guess, I will echo back a lost consisting of\n"
"0's and 1's, with a 1 in a given position meaning that\n"
"you guessed the number, and a zero meaning that you didn't.\n"
"For example, if the actual solution was 2 3 6 1, I'll respond\n"
"\t 1 0 0 1\n"
"See how many guesses it takes you to get the solution!\n\n"
"If you want to give up, type a negative number for one of\n"
"your guesses, and we'll tell you what the pattern was.\n\n";
}
int main() {
offer_help();
srand(time(0)); // Initialize random numbers with current time as seed
while(play_one_game()); // if play_one_game returns true, play again
}
bool play_one_game() {
std::vector<int> solution(4); // Four solutions for our guessing game
std::vector<int> guess; // User guesses
for(unsigned i = 0; i < solution.size(); ++i)
solution[i] = rand() % 10;
int trial_number = 0; //int that shows what guess the user is on
bool keepPlaying = true;
while(keepPlaying){
std::cout << "Guess #" << ++trial_number << "? ";
guess.clear(); // Clear old guesses
for(unsigned i = 0; i < solution.size(); ++i){
int guess_input;
//outputs error if user inputs a letter.
if (!(std::cin >> guess_input)) {
std::cerr << "Bad input data! Feed me numbers!\n";
std::cerr << "Try again!" << std::endl;
std::cin.clear(); // Clear flags
continue;
}
if (guess_input < 0){
std::cout << "Too bad! Solution was " << std::endl;
for(unsigned i = 0; i < solution.size(); i++)
std::cout << (solution[i]);
keepPlaying = false;
break;
}else
guess.push_back(guess_input);
}
if(!keepPlaying)
break;
if(solution.size() != guess.size()){
std::cerr << "Wrong number of guesses, try again!" << std::endl;
continue;
}
//determines if user correctly guessed any of the
//numbers and tells the user which is correct.
bool correct = true;
for (unsigned i = 0; i < solution.size(); i++) {
if (guess[i] == solution[i])
std::cout << 1 << " ";
else{
correct = false;
std::cout << 0 << " ";
}
}
if(correct){
std::cout << "Congratulations - you won!" << std::endl;
break;
}
std::cout << std::endl;
}
int replay = -1;
do{
// Ask user for input until input is 0 or 1
std::cout << std::endl << "Play again (0/1)? ";
std::cin >> replay;
}
while(replay != 0 && replay != 1);
return static_cast<bool>(replay); // return user replay answer (false/true)
}
Try to keep your code as simple as possible. Welcome to SO. And don't expect future answers to be that excessive.
You're never inserting anything into your solution vector. You just declare the vector, and then say:
for(int i = 0; i < solution.size(); ++i)
solution[i] = randint(10);
...which won't do anything since at this point solution.size() == 0. Later, when you iterate over your result vector, you end up accessing invalid elements in your empty solution vector. You also can't assume that the result vector and solution vector are the same size.