Having trouble looping through an array in c++ [closed] - c++

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 4 years ago.
Improve this question
I seem to be looping through my array wrong, I've got it set up to prompt the user for a list of numbers and I am supposed to be comparing it to another number that the user sets.
#include <iostream>
using namespace std;
bool chk = true;
int main() {
/*
Write a program that asks the user to type 10 integers of an array and an integer s.
Then search the value s from the array and display the value of s if it is found in
the array otherwise print sorry not found..
*/
int userArray[10], i, greater = 0;
int s;
cout << "Enter a check number: \n";
cin >> s;
if (chk = true) {
//prompt for array list
for (i = 0; i < 9; i++) {
if (i == 0) {
cout << "Enter ten numbers: " << "\n";
cin >> userArray[i];
}
else {
cin >> userArray[i];
}
chk = false;
}
//loop through the array
for (int i = 0; i <= 10; i++) {
if (s = userArray[i]) {
//for testing
cout << userArray[i];
//cout << s;
}
else {
cout << "No match found!";
}
//I was just using this to pause the console and let me inspect result
cin >> greater;
return 0;
}
}
}
I assume the following code is where the problem lies. The idea is i set s = 2 enter in a list of numbers and then compare to s and print s if there is a match if not I print No match found. When I enter in a number that i know matches s it seems to print the first number in the array, but i thought since I loop through the numbers one by one in the for loop that it should display when it reaches the right number not when it stops. Thanks in advance
//loop through the array
for (int i = 0; i <= 10; i++) {
if (s = userArray[i]) {
//for testing
cout << userArray[i];
//cout << s;
}
else {
cout << "No match found!";
}

You are using a single equals sign. This is setting s to userArray[i] so it always evaluates to true. For comparisons, use double equal signs, like this:
if (s == userArray[i]) {...}
Also, your return statement is inside your loop (credit to #UnholySheep).

you are comparing with a single assignment operator = you should be using the equal operator instead ==
if (s = userArray[i]) with in the for loop is one example.
you also doing the same mistake in
if (chk = true)

Related

How to correctly implement a while loop that reads a sequence of inputs? [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 5 months ago.
Improve this question
Write a while loop that sums all integers read from input until a negative integer is read. The negative integer should not be included in the sum.
Ex: If input is 20, 45, 34, 5, -44, then the output is:
104
#include <iostream>
using namespace std;
int main() {
int numInput;
int numInts;
numInts = 0;
cin >> numInput;
while (numInput >= 0) {
cout << numInts << endl;
numInts = numInts + numInput;
}
cout << numInts << endl;
return 0;
}
The problem is that currently the condition inside the while loop doesn't depend on anything that you do inside the loop.
To solve this you can move the cin >> numInput to inside the condition as shown below:
int main() {
int numInput;
int sum = 0;
//take input and check it
while (cin >> numInput && numInput >= 0) {
sum += numInput;
std::cout <<"current sum is: "<<sum <<std::endl;
}
cout << sum << endl;
return 0;
}
Demo
The loop terminates when numInput is less than 0. In your code you read only one number. So if that number is greater than zero then you get an infinite loop because you never read a second number.
Your code should look something like this
cin >> numInput; // read the first number
while (numInput >= 0) {
cout << numInts << endl;
numInts = numInts + numInput;
cin >> numInput; // read the next number
}
See how the above code reads a new number each time around the while loop. This way when a negative number is entered the loop will terminate.

Reversing a vector using functions [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 2 years ago.
Improve this question
I'm trying to reverse a vector using functions but whenever I run the program it terminates and outputs nothing. Can anyone please tell me what I am doing wrong?
#include <iostream>
#include <vector>
using namespace std;
void reverseavector(vector<int>& vec)
{
for (int i = vec.size() - 1; i >= 0; --i) {
cout << vec[i];
}
}
int main()
{
int input;
vector<int> vect;
cout << "Enter values to reverse the vector" << endl;
cin >> input;
for (int i = 0; i < vect.size(); ++i) {
vect.push_back(input);
}
reverseavector(vect);
return 0;
}
In your code, you declared the following statement:
vector<int> vect;
This statement means that a vector of integers named vect get created, but you didn't specify a size for it, therefore when the following loop is reached:
for (int i = 0; i < vect.size(); ++i){
vect.push_back(input);
}
vect.size() return 0 because you didn't specify a size for vect, therefore the loop never gets executed. Because the condition is false.
I made some changes to the code you have. Take a look:
#include <iostream>
#include <vector>
using namespace std;
void reverseavector(vector<int>& vec)
{
for (int i = vec.size() - 1; i >= 0; --i) {
cout << vec[i];
}
}
int main()
{
int input;
vector<int> vect;
bool stop = false; // This bool will keep allow the while loop to keep prompting the user to enter a number until the input is -1
while (stop == false)
{
cout << "Enter a value to the vector to be reversed, or -1 to stop entering values" << endl;
cin >> input;
vect.push_back(input);
if (input == -1)
{
stop = true;
}
}
reverseavector(vect);
return 0;
}
The main thing about your code is that you needed a way to loop taking values into input. There are other ways to do this, but this was the first one I came up with.
When you run
vector<int> vect;
cout << "Enter values to reverse the vector" << endl;
cin >> input;
for (int i = 0; i < vect.size(); ++i)
vect.size() remains at 0, because the vector is empty. So, i < vect.size() remains false, and the loop doesn't enter.
So, reverseavector gets an empty vector and outputs nothing.

c++: for not working as intended [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 5 years ago.
Improve this question
My question is when I run the code,and call for the list,so I press 3,nothing happens and it just skips over the code in for(). Why does this occur and how can I fix it?
Simple code would be welcome.I am now to this.
The first two int before the main checks if the student is qualified for the school,or not.i tested those and they are working great.
The struct describes a student.He/She has a name(nev),marks (bacmagy,bacrom,bacmat,bacvalasz).A boolean value(langexam) is present,to represent is the student has a language exam or not.
bsiker is true,if the formula in calculateBac turns out to be true.
atmente is true,if bsiker and langexam are both true.
The listing would spit out the name,bsiker and atmente.
#include <iostream>
using namespace std;
int atmegye(bool elso, bool masodik){
if (elso && masodik)
return true;
else
return false;
}
int calculateBac(double magy, double mat, double rom, double val){
double osszeg = magy + mat + rom + val;
osszeg = osszeg / 4;
if (magy < 5 || mat < 5 || rom < 5 || val < 5 || osszeg < 6)
return false;
else
return true;
}
int main(){
struct diak{
char nev[32];
bool langexam, atmente, bsiker;
double bacmagy, bacrom, bacmat, bacvalasz, bac;
};
diak v[150];
bool cap = false;
int opcio;
int j, n = 0;
int i = 0;
do{
cout << "\n Welcome. \n 1-new studient \n 2-Change a studient's details \n 3-List \n 4-Exit \n";
cin >> opcio;
switch (opcio){
case 4:{
return 0;
}
case 1:{
cout << "Please give the name of the student: ";
cin >> v[i].nev;
cout << "Hungarian mark: ";
cin >> v[i].bacmagy;
cout << "Romanian mark: ";
cin >> v[i].bacrom;
cout << "Maths mark: ";
cin >> v[i].bacmat;
cout << "Optional mark: ";
cin >> v[i].bacvalasz;
cout << " Do you have a language exam? Please respond with 1 or 0: ";
cin >> v[i].langexam;
v[i].bsiker = calculateBac(v[i].bacmagy, v[i].bacrom, v[i].bacmat, v[i].bacvalasz);
v[i].atmente = atmegye(v[i].bsiker, v[i].langexam);
i = i + 1;
i = n;
cout << n;
break;
}
case 3: {
for(i = 0; i < n; i++)
cout << v[i].nev << " " << v[i].bsiker << " " << endl;
break;
}
}
}while (opcio != 5);
}
This line is wrong:
i = n;
it should be:
n = i;
Your code is just undoing the i = i + 1; line that precedes it.
n is initialized as 0 and never set to any other value. Therefore your for loop is not supposed to run any iteration
The problem is in the for loop's conditional. You initialized the value of n to 0, and that value never seems to change. The variable i is also initialized to 0 inside the for loop. When the user chooses option 3, the for loop conditional ( 0 < 0) is evaluated which is false, so the for loop is skipped every time. So, to fix this problem, you need to update the value of n somewhere in your code, or you need to change your conditional statement. Hope this helps!
I know this probably won't help for your assignment, but here's a (one of many) way to handle this is a more c++-like manner, and without using OOP.
The standard library and the c++ type system give us plenty of useful tools to avoid writing bugs in the first place (that's really nice!), and find the one that are left at compile-time (saves a ton of time!). That's what the biggest difference between c and c++ is, and it is a very important one.
#include <iostream>
#include <vector>
#include <string>
#include <string.h>
// fixed-size record to save in data file, for example.
struct diak{
char nev[32];
bool langexam, atmente, bsiker;
double bacmagy, bacrom, bacmat, bacvalasz, bac;
};
void atmegye(diak& student)
{
student.atmente = student.bsiker && student.langexam;
}
void calculateBac(diak& student) // computes grades average, checks if passed.
{
double osszeg = student.bacmagy + student.bacmat + student.bacrom + student.bacvalasz;
student.bac = osszeg / 4.0;
student.bsiker = student.bacmagy >= 5
&& student.bacrom >= 5
&& student.bacmat >= 5
&& student.bacvalasz >= 5
&& student.bac >= 5; // this last test unnecessary, but rules are rules.
}
void AddNewStudent(std::ostream& os, std::istream& is, std::vector<diak>& students)
{
diak new_student;
std::string temp;
while(temp.empty())
{
os << "Student name: ";
is >> temp; // using a temp buffer avoids out of bounds errors
}
if (temp.length() >= sizeof(new_student.nev))
temp.resize(sizeof(new_student.nev) - 1);
strcpy(new_student.nev, temp.c_str());
// input values below SHOULD be validated for range (0-100)
// or whatever makes sense for your school.
os << "Hungarian mark: "; is >> new_student.bacmagy;
os << "Romanian mark: "; is >> new_student.bacrom;
os << "Maths mark: "; is >> new_student.bacmat;
os << "Optional mark: "; is >> new_student.bacvalasz;
// example validation. Validating user input is the worst!
// above ^^^ grades ^^^ can use a common function for validation.
for(;;)
{
os << " Do you have a language exam? Please respond with 1 or 0:";
is >> temp;
if (temp == "0")
{
new_student.langexam = false;
break;
}
if (temp == "1")
{
new_student.langexam = true;
break;
}
// not a valid entry, try again!
}
calculateBac(new_student);
atmegye(new_student);
students.push_back(new_student);
}
void EditSudent(std::ostream& os, std::istream& is, std::vector<diak>& students)
{
// query which student then edit using streams 'os' and 'is' for i/o.
}
// could also be used to write to file...
void PrintStudents(std::ostream& os, const std::vector<diak>& students)
{
// maybe by printing a student number you could reuse this
// function from EditStudent()...
//
// At the same time, it is only 2 lines of code. You decide.
for(size_t i = 0; i < students.size(); i++)
os << students[i].nev << " " << students[i].bsiker << "\n";
os.flush();
}
int main()
{
std::vector<diak> students; // could also be an std::list<>
while(true) // 1 less line of code than do {...} while, and easier to read.
{
int opcio = 0;
std::cout << "\n Welcome."
"\n 1-new studient"
"\n 2-Change a studient's details"
"\n 3-List "
"\n 4-Exit \n";
std::cin >> opcio;
switch (opcio)
{
case '1':
AddNewStudent(std::cout, std::cin, students);
break;
case 2:
EditSudent(std::cout, std::cin, students); // << queries student and edit that
break;
case 3:
PrintStudents(std::cout, students);
break;
case 4:
return 0;
}
}
}
Note how the tasks are very well delimited into their own function, this also helps finding bugs faster, as it makes the code easier to read and reason about (the famous divide and conquer strategy).
Having the students array (or list) as a single entity simplifies its management, no extra variable to keep up to date, etc...
In a more serious application, the input validation would be best done using a template, and would give the user an escape character so he could cancel adding the new student at any time.

Vector is not clearing [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 7 years ago.
Improve this question
I have created a function that gets a series of guesses (a sequence of colors) from a user and puts them in a vector, and this function is called within a while loop in main().
Each time it is called by the while loop, the guess should be cleared before being refilled with inputs. However, within the second loop, entering a color I entered during the first loop activates my error message ("Invalid or repeated color entry..."), suggesting that the vector was not successfully cleared.
I've tried to clear it with a space, various strings, etc., but nothing seems to clear it. What am I missing?
Function:
void getGuess(vector<string> &currentGuessPegs, vector<string> &colorChoices, int maxPegSlots) {
string input; // stores input temporarily
// ---clear previous guess---
for (int i = 0; i < maxPegSlots; i++) {
currentGuessPegs[i] == "";
}
// ---prompt player for each peg guess and store in currentGuessPegs---
for (int i = 0; i < maxPegSlots; i++) {
cout << "Peg " << i+1 << ": ";
cin >> input;
while (find(currentGuessPegs.begin(), currentGuessPegs.end(), input) != currentGuessPegs.end() // Loops if color entry has already been used
|| find(colorChoices.begin(), colorChoices.end(), input) == colorChoices.end()) { // or is an invalid choice
cout << "Invalid or repeated color entry. See color choices and re-enter a color you have not used.\n";
cout << "Peg " << i + 1 << ": ";
cin >> input;
}
currentGuessPegs[i] = input;
}
}
And here is my call to the function from main():
// ---get and check guesses until maximum # of guesses is exceeded or solution is guessed---
while (guessCount < maximumGuesses && solutionGuessed == false) {
getGuess(currentGuess, colorOptions, numberOfPegs); // get the guess
solutionGuessed = checkGuess(currentGuess, solution, numberOfPegs, red, white); // check the guess; returns true if solution was guessed
cout << "r: " << red << " w: " << white << endl << endl;
guessCount++;
}
currentGuessPegs[i] == "";
// ^^
Whoops.

C++ For-Loop Gets stuck when entering new variables [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm new to C++ and trying to create a lottery game for a college project.
I have a for loop to check that there are no duplicate numbers in the array entered. This works absolutely fine when you take out the section of code to produce the random numbers.
As soon as I add the random number section back in, the for loop just gets stuck. It will continuously tell me that i have already entered the number when its trying to store the first number.
I have attached all of my code, apologies if you don't need it all.
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
using namespace std;
//int loto[6];
int main()
{
int numbers[6];
//void rand_num(int loto[6], int count);
int loto[6]; //used to store the loto numbers
//int james = 0;
//int l,j; //used in checking any duplicated
srand(time(0));
for(int count=0; count<6; count++)
{
loto[count] = (rand()%49)+1;
cout << loto[count] << endl;
}
//declares the variable i to increase each time a number is entered.
//this will only go as high as 6
for(int i=0;i<6;i++)
{
cout<<" " << i<<" : Please enter your lottery numbers: "<<endl;
cin>>numbers[i];
if ((numbers[i] >= 50) | (numbers[i] == 0))
do
{
{
//checks to see if the first number entered is above 50 or = to 0 and rejects it
cout << "The Number must be between 1-49, please select again. " << endl;
cin >> numbers[i];
}
}
while ((numbers[i] >= 50) | (numbers[i] == 0));
//----------------------------------------------------------------------------
//this section of code is a loop within a loop to check the number entered against all numbers already stored.
//makes l the same as i effectively
for(int l=0;l<6;l++)
{
//makes j one more than l
for(int j=l+1;j<7;j++)
{
if( numbers[l] == numbers[j] )
do
{
{
cout << "Number has already been chosen, please re-enter number " << endl;
cout << endl;
cin >>numbers[i];
//checks the number that is re-entered is not <50 or = 0
//if so it rejects it and asks for another as above.
if ((numbers[i] >= 50) | (numbers[i] == 0))
do
{
{
cout << "The Number must be between 1-49, please select again. " << endl;
cin >> numbers[i];
}
}
while ((numbers[i] >= 50) | (numbers[i] == 0));
}
}
while (numbers[l] == numbers[j]);
}
}
}
//----------------------------------------------------------------------------
//this displays the numbers that have been chosen.
cout << "Your Numbers are: " << endl;
for (int i = 0; i<6; i++)
{
cout << " " << numbers[i];
}
return 0;
}
I'm not sure this is the real problem but it is a bug. Try to correct it and see if it helps.
for(int l=0;l<6;l++)
{
//makes j one more than l
for(int j=l+1;j<7;j++)
{
if( numbers[l] == numbers[j] )
The inner-loop will reach j==6 so you will access outside the array. The outer-loop shall have 5 as the limit and the inner-loop shall have 6 as the limit.
EDIT:
After looking a bit more at your code I can see that you are using numbers[] without initializing it. The two nested for-loops will compare all elements in numbers. But if the user have only entered 2 numbers, the rest is unitialized and can give unintended results.
Further - you don't need to check all elements againt all elements every time. Just check the newly entered number (index by i) with all previous numbers.
Finally you will probably need something like:
if (!(cin >> numbers[i])) {
cout << "Please enter numbers only." << endl;
cin.clear();
cin.ignore(10000,'\n');
}
to handle input not being integer, e.g. "text"
And to minor things:
You should also check for negative numbers.
You are using | instead of ||. It will work fine but || seems more correct as it is the logical OR (while | is a binary OR).