Quit while (true) loop 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 2 years ago.
Improve this question
This is my simple while (true) loop:
while (true)
{
int i = 0;
++i;
cout << i << endl;
if (i == 5) {
break;
}
}
}
So break; isn't quitting the loop and the output is an infinite 1.

See this for Why use a for loop instead of a while loop?.
Now, coming to your question:
You are initializing i variable in each iteration of your while loop. Move the definition of i outside the while loop so that it's value can be updated.
Try this:
#include <iostream>
int main(void)
{
int i = 0;
while (true)
{
++i;
std::cout << i << std::endl;
if (i == 5)
break;
}
return 0;
}
Output:
1
2
3
4
5
Suggestion:
You can also use for loop as it is more appropriate to print a range of numbers.
#include <iostream>
int main(void)
{
for (int i = 1; i <= 5; i++)
std::cout << i << std::endl;
return 0;
}

The i is always initialized to 0 on each iteration. You should use this outside of the loop.

You are creating a new variable i in every run of the loop.
It is initalized to zero, then you increase it by one.
So after
int i = 0;
++i;
the variable i is always 1.
Solution:
int i = 0;
while (true) {
{
++i;
cout << i << endl;
if (i == 5) {
break;
}
}
}
or you can just use a simple for-loop:
for (int i = 0; i <= 5; i++)
{
cout << i << endl;
}

Related

Why does this code snippet print 10 infinitely in c++11? [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 last year.
Improve this question
Why does the following C++ code snippet keep printing 10 indefinitely?
int num = 10;
while (num >= 1)
cout << num << " ";
num--;
Your snippet is the equivalent of this when using braces:
int num = 10;
while (num >= 1)
{
cout << num << " ";
}
num--;
Meaning only the printing statement is part of the loop. What you want is this:
int num = 10;
while (num >= 1)
{
cout << num << " ";
num--;
}
If you want to use a while loop in c ++ you will have to enclose the inner code between {}, like this:
while(/* Condition */){
// Do something
}
You might be familiar with python, though in c++ scoping ain't linked to indentation.
With correct indentation, it would look the following:
int num = 10;
while (num >= 1)
cout << num << " ";
num--;
I would really recommend a formatting tool like clang-format here, as it would immediately gave you this feedback.
Scopes in C++ are done using {}.
As such, the code should be:
int num = 10;
while (num >= 1)
{
cout << num << " ";
num--;
}
If you don't specify the {}, only the next statement is part of the scope.
In this case, I guess you are trying to learn while loops. Though this code is better fit for a for-loop.
int num = 10;
for (int num = 10; num >= 1; num--)
cout << num << " ";

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.

no instance of overload function "get" matches the arguent list [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 3 years ago.
Improve this question
so i have been stuck with this for hours and might be too big of a dummy to find a solution myself so...
i am getting an error: "no instance of overload function "get" matches the arguent list","argument types are: (char)"
the code im trying to run is:
#include <iostream>
#include <fstream>
#include <string>
#include <tuple>
#include <vector>
using namespace std;
bool checkIfLowercase(string word) {
for (int i = 0; i < word.length(); i++) {
if (!islower(word[i])) {
return false;
}
}
return true;
}
int simpleScore(string word) {
int wordScore=0;
for (int i = 0; i < word.length(); i++) {
string letter(1, word[i]);
if (letter == "a")
wordScore = wordScore + 1;
if (letter == "e")
wordScore = wordScore + 1;
if (letter == "i")
//continues for other letters
else {
wordScore = wordScore + 0;
}
}
return wordScore;
}
int main()
{
ifstream fileWithEverything("test.txt");
string wordFromFile;
int amountOfWords=0;
int x;
vector<tuple<string, int>> vectorWithTuples;
while (getline(fileWithEverything, wordFromFile)) {
if (checkIfLowercase(wordFromFile) == true) {
//cout << wordFromFile << endl;
amountOfWords++;
x = simpleScore(wordFromFile);
//cout << x << endl;
vectorWithTuples.push_back(make_tuple(wordFromFile, x));
}
}
for (int i = 0; i < wordFromFile.length(); i++) {
cout << get<0>(wordFromFile[i]) << " ";
cout << get<1>(wordFromFile[i]) << endl;
}
cout << "Amount of words is: "<<amountOfWords << endl;
}
how do i get rid of the error???
i have recentrly started coding so please dont be too harsh on me in the comments but do point out my mistakes :D
wordFromFile is a string. std::get works on tuples.
how do i get rid of the error???
Did you mean get<0>(vectorWithTuples[i]) instead?

Having trouble looping through an array in c++ [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 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)

Why is my loop in my recursive function infinite? [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 8 years ago.
Improve this question
I have the following function that recursively checks each square in a sudoku puzzle to make it legal, and I kept getting a segmentation fault when it ran, so I put cout checks everywhere to see where it broke. Somehow, it stays in the loop and continues to call the addSquare function over and over, without ever ending. How do I get it to stop?
bool DoTheWork::addSquare(int& depth)
{
depth++;
cout << depth << endl;
if(board.checkZeroes()==false){ //if the game is won, return true
cout << "ifstatement1" << endl;
return true;
}
else {
for(int i = 0; i < 10; i++) {
cout << "loop1" << endl;
for(int j = 0; j < 10; j++) {
cout << "loop2" << endl;
if(this->board.getSquare(i,j)==0) { //go through each
cout << "ifstatement2" << endl;
for(int k = 1; k < 10; k++) {
cout << "loop3" << endl;
//try each number in that square for legality
board.setSquare(i,j,k);
//set that square to the number you are currently on
if(board.isLegal()==false) {
cout << "ifstatement3" << endl;
board.unsetSquare(i,j);
}
//if the board is not legal for that number, unset that square
if(addSquare(depth)==true) {
cout << "ifstatement4" << endl;
return true;
}
//recursive function, if method is true then it will return true
board.unsetSquare(i,j);
}
}
}
}
}
return false;
} // bool DoTheWork::addSquare(int& depth)
When run in the terminal, it prints the following:
loop 1
loop 2
ifstatement2
loop3
ifstatement3
130964
loop1
...
and onwards until it says "Segmentation fault (core dumped)"
The number after "ifstatement3" increases by 1 each time the depth increases.
Including the checkZeroes function below:
bool Board::checkZeroes()
{
bool zeroPresent = false;
//assume there are no zeroes, easier for coding
for(int i=0; i<9; i++) {
for(int j=0; j<9; j++) {
if(theBoard[i][j] == 0){
//go through each value of theBoard, if any are 0 return true
zeroPresent = true;
}
}
}
return zeroPresent;
} // int Board::checkZeroes()
You never change the value of depth that will cause infinite recursion and a segmentation fault will happen when the stack access memory that should not be accessed.
I would run it in a debugger like GDB or DDD in linux.