If statement still going through when my condition should be false [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 1 year ago.
Improve this question
I am attempting to write a Caesar encryption program. I have written two functions.
The first (sanitize) allows me to make sure that all strings are fully capitalized, here is the source code.
string sanitize(string message) {
for(int i; i < message.length(); i++){
message[i] = toupper(message[i]);
}
return message;
}
The second (caesar) encrypts the message given. Here is the source code for that as well.
string caesar(string c_message, char direction) {
if (direction = 'R') {
for(int j; j < c_message.length(); j++) {
if((int)c_message[j] + 3 > 90) {
c_message[j] = (char)(64 + (3 - (90 - (int)c_message[j])));
} else {
c_message[j] = (char)((int)c_message[j] + 3);
}
}
} else if (direction = 'L') {
for(int i; i < c_message.length(); i++) {
if((int)c_message[i] - 3 < 65) {
c_message[i] = (char)(91 - (3 - ((int)c_message[i] - 65)));
} else {
c_message[i] = (char)((int)c_message[i] - 3);
}
}
} else {
cout << "directions: 'L' or 'R'" << endl;
}
return c_message;
}
An example of execution :
int main(){
cout << sanitize("HELLO") << " " << (char)3 << endl;
cout << caesar("HELLO", 'L') << endl;
return 0;
}
The first if statement works, but the second does not.

if (direction = 'R') {
} else if (direction = 'L') {
These lines are wrong. = in C++ is an assignment operator and it sets the value of a variable in lefthand to the value of righthand. Then, it is evaluated to the new (righthand) value. Another point is that nonzero values are considered as true when used as condition.
You should use a comparision operator == instead of that like this:
if (direction == 'R') {
} else if (direction == 'L') {

Related

Using if statement if not multiple [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
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.
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.
Improve this question
I want to create a 5x5 array of '' with a hashtag in the center instead of '', but only when the user inputs either 'a' or 'b.' On the area I marked "RIGHT HERE" it doesn't work unless its ONLY 'a' / ONLY 'b', so what do I do? Thank you in advance!
#include <iostream>
using namespace std;
int main()
{
while (true){
///Variables:
char array[4][4]; //Playing field 5x5
char direc; //Direction player moves
for (int x = 0; x <=4; x++){
for (int y = 0; y <= 4; y++){
array[x][y] = '_';
if (direc != 'a' || 'b'){ ///RIGHT HERE!
array[2][2] = '#';
}
cout << array[x][y]; //Starts printing Board
if (y == 4){
cout << endl; //Cuts to next line on print if 4 in a column row
}
}
}
cin >> direc;
cin.get();
}
}
Did not check the required logic of your statement or of the other parts of your program, but your marked statement should be written as
(direc != 'a' || direct != 'b')
Your statement (direc != 'a' || 'b') will always evaluate to true, since 'b' as the second operand of the logical or operator || is an integer value > 0 (representing character b in some encoding) and therefore treated as true.
As Neil mentioned in the comment, ur 5x5 field is in fact 4x4, so u are only able to access array[0][0] up to array[3][3], while your X and Y are 4 at some point. You should use this instead:
char array[5][5]
so that u can access your array up to index 4
hope that helps you
#include <iostream>
using namespace std;
int main()
{
///Variables:
char array[5][5]; //Playing field 5x5
char direc; //Direction player moves
char player;
while (true) {
//get direc
cin >> direc;
cout << direc << "\n";
if (direc == 'a' || direc == 'b') { ///RIGHT HERE!
player = '_';
}
else {
player = '#';
}
for (int x = 0; x <= 4; x++) {
for (int y = 0; y <= 4; y++) {
array[x][y] = '_';
if (x == 2 && y == 2) {
array[x][y] = player;
}
cout << array[x][y]; //Starts printing Board
if (y == 4) {
cout << endl; //Cuts to next line on print if 4 in a column row
}
}
}
}
}

C++ error returning a string from a function [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'm trying to return a string from the function solution() but I am getting the error below. Apologies if this is pretty basic but could anybody explain how to return the string. I understand that it is related to pointers.
error: could not convert ‘(std::__cxx11::string*)(& hexaDeciNum)’ from
‘std::__cxx11::string* {aka std::__cxx11::basic_string*}’ to
‘std::__cxx11::string {aka std::__cxx11::basic_string}’
string solution(string &S){
int n = stoi(S);
int answer = 0;
// char array to store hexadecimal number
string hexaDeciNum[100];
// counter for hexadecimal number array
int i = 0;
while(n!=0)
{
// temporary variable to store remainder
int temp = 0;
// storing remainder in temp variable.
temp = n % 16;
// check if temp < 10
if(temp < 10)
{
hexaDeciNum[i] = temp + 48;
i++;
}
else
{
hexaDeciNum[i] = temp + 55;
i++;
}
n = n/16;
}
// printing hexadecimal number array in reverse order
for(int j=i-1; j>=0; j--){
//cout << hexaDeciNum[j] << "\n";
if (hexaDeciNum[j].compare("A") ==0 or hexaDeciNum[j].compare("B") ==0 or hexaDeciNum[j].compare("C") ==0 or hexaDeciNum[j].compare("D") ==0 or hexaDeciNum[j].compare("E") ==0 or hexaDeciNum[j].compare("F") ==0 or hexaDeciNum[j].compare("1") ==0 or hexaDeciNum[j].compare("0") ==0 ) {
answer = 1;
}
}
if (answer == 1){
return hexaDeciNum;
}
else {
return "ERROR";
}
}
int main() {
string word = "257";
string answer = solution(word);
return 0;
}
hexaDeciNum is defined as string hexaDeciNum[100]. It is not a string - it is an array of 100 string instances.
You're attempting to return it from a function that should return string.
You should define hexaDeciNum as string hexaDeciNum; instead of string hexaDeciNum[100];. With that way, you can still indexing operator. However you can not use compare method anymore, because each element of string is a char. Instead use operator == like in the following for your piece of code.
// printing hexadecimal number array in reverse order
for(int j=i-1; j>=0; j--){
//cout << hexaDeciNum[j] << "\n";
if (hexaDeciNum[j] == 'A' or hexaDeciNum[j]=='B' or
hexaDeciNum[j] == 'C' or hexaDeciNum[j] == 'D' or
hexaDeciNum[j] == 'E' or hexaDeciNum[j] == 'F' or
hexaDeciNum[j] == '1' or hexaDeciNum[j] == '0' ) {
answer = 1;
}
}
and please don't forget to compile it for c++ 11 with -std=c++11 option of compiler.

c++ getting weird crashes in my program [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
#include <iostream>
using namespace std;
int main()
{
int a = 0, skrb = 0, j = 0;
char b, simboliai[2000];
char zodis[50][20];
char check[1][20] = {'f'};
cout << "Prasome irasykite sakini: ";
cin.getline(simboliai,sizeof(simboliai));
//----------------- Zodziu skaidymas ----------------------------------------------------------------------------------------------------------
a = 0;
for (int i = 0; i > -1; i++)
{
if ((simboliai[i] == 's' && simboliai[i++] == ' ') || (simboliai[i] == 's' && simboliai[i++] == '\n'))
{
check[0][a] = 't';
}
if (simboliai[i] == ' ')
{
a++;
}
else
{
zodis[i][a] = simboliai[i];
}
if (simboliai[i] == '\n')
{
break;
}
}
a = 0;
while (1)
{
if (simboliai[a] == '.' || simboliai[a] == ',' || simboliai[a] == '!' || simboliai[a] == '?')
{
skrb++;
}
a++;
if (simboliai[a] == '\n')
{
break;
}
}
a = 0;
cout << "Jus ivedete tokius zodius kurie baigiasi raide 's'" << endl;
while(1)
{
if (zodis[j][a] == 'Ì')
{
cout << '\n';
a++;
}
if (check[0][a] == 't')
{
cout << zodis[j][a];
}
if (zodis[0][a] == 'Ì')
{
break;
}
}
cout << "Pas jus yra (.','!'?) simboliu: " << skrb << endl;
cin.ignore();
cin.get();
}
Basically this program would work but that for part just ruins everything. It doesn't put characters one by one. And when I debug it shows that program have put symbol in its place but then there is Ì.
So it looks just like so
input: word word
zodis[0][0] goes like wÌÌÌÌÌÌÌÌÌÌ zodis [1][0] goes oÌÌÌÌÌÌÌÌÌÌ and so on and it breaks. Thank you in advance.
If you are saying the for loop wouldn't put characters 1 by 1, it was in your "simboliai[i++] == ' '" logic. integer 'i' been incremented twice each loop when current character is 's' which mean it will be incremented from i=2 to i=4 if simboliai[i] = 's'. Use i+1 instead for your checking.
for (int i = 0; i > -1; i++)
{
...
}
is the main problem. There might be others but I don't look too closely for them.
The values of i will be 0, 1, 2. etc.
All of them are greater than -1.
The loop will go on until the value i reaches INT_MAX. (Not sure what happens when i is incremented at that time).
That is way larger than the size of the array simboliai anyway. Your program will access the array simboliai beyond valid limits and cause undefined behavior.
I think what you need is:
size_t len = strlen(simboliai);
for (size_t i = 0; i < len; i++)
{
...
}
Other Problems
Some of the errors result from the assumption that there is a newline character in simboliai. That assumption is not correct. std::istream::getline reads and discards the newline character.
If Google Translate is correct, zodis is supposed to contain a list of words. When you are iterating over the characters of simboliai, you need three counters.
One to iterate over the characters of simboliai.
One to keep track of the number words.
One to keep track of the number of characters in the current word.
Your for loop is not doing that.
When you are trying to access the contents of an array, you need to always write defensive code and make sure that you never access the array using out of bounds indices. In the last while loop, you are not doing that.
In the last while loop, you are incrementing a only in the first if block. If the conditional of that if statement evaluates to false, a never gets incremented and you get stuck in an infinite loop.
In the last loop you use j as an index but its value is initialized to 0 at the start of the function and never gets updated. It's not clear what the intent of the last while loop is. Hence, I can't say whether it's a bug but it sounds like it could be.
Here's a cleaned up version of your posted code with still a few unknowns.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int a = 0, skrb = 0, j = 0;
char b, simboliai[2000];
char zodis[50][20];
char check[1][20] = {'f'};
cout << "Prasome irasykite sakini: ";
cin.getline(simboliai,sizeof(simboliai));
//----------------- Zodziu skaidymas ----------------------------------------------------------------------------------------------------------
int word_counter = 0;
a = 0;
size_t len = std::strlen(simboliai);
for (size_t i = 0; i < len; i++)
{
if ((simboliai[i] == 's' && simboliai[i+1] == ' ') || (simboliai[i] == 's' && simboliai[i+1] == '\0'))
{
check[0][a] = 't';
}
if (simboliai[i] == ' ')
{
zodis[word_counter][a] = '\0';
a = 0;
++word_counter;
}
else
{
zodis[word_counter][a] = simboliai[i];
++a;
}
}
a = 0;
while ( simboliai[a] != '\0' )
{
if (simboliai[a] == '.' || simboliai[a] == ',' || simboliai[a] == '!' || simboliai[a] == '?')
{
skrb++;
}
a++;
}
a = 0;
cout << "Jus ivedete tokius zodius kurie baigiasi raide 's'" << endl;
while( j < 50 && a < 20 )
{
if (zodis[j][a] == 'Ì')
{
cout << '\n';
}
if (check[0][a] == 't')
{
cout << zodis[j][a];
}
if (zodis[0][a] == 'Ì')
{
break;
}
a++;
}
cout << "Pas jus yra (.','!'?) simboliu: " << skrb << endl;
cin.ignore();
cin.get();
}

Use '&' to create pointer to member error [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 am creating a game in c++ and I have called a function, however I am getting an error saying i need to insert an ampersand to create a pointer to a member. However, I am unsure where this needs to go...
string MouseAndCatGame::prepareGrid(){
//prepare a string that holds the grid information
ostringstream os;
for (int row(1); row <= SIZE; ++row) //for each row (vertically)
{
for (int col(1); col <= SIZE; ++col) //for each column (horizontally)
{
if ((row == cat_.getY) && (col == cat_.getX))
{
os << cat_.getSymbol(); //show cat
}
else
if ((row == mouse_.getY()) && (col == mouse_.getX()))
os << mouse_.getSymbol(); //show mouse
else
{
bool holePresent(underground_.findHole(col, row));
if (holePresent == true) // If there is a hole at that location
{
os << HOLE; // Show hole symbol
}
else
{
if ((row == nut_.getY()) && (col == nut_.getX()))
{
os << nut_.getSymbol(); //show mouse
}
else
{
os << FREECELL;//show free grid cell
}
}
}
} //end of col-loop
os << endl;
} //end of row-loop
return os.str();
} //end prepareGrid
The error is specifically the following:
Cat::getY': non-standard syntax; use '&' to create a pointer to member
It looks like you don't want a pointer to member. You just forgot the parentheses on your function call.
if ((row == cat_.getY()) && (col == cat_.getX()))
assuming getY/getX are methods of cat_ and not poorly named public variables,
this
if ((row == cat_.getY) && (col == cat_.getX))
should be
if ((row == cat_.getY()) && (col == cat_.getX()))

Iteration counter not incrementing [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 8 years ago.
Improve this question
I wrote a program in c++ to print all the primes up to 100, but it just writes "hello world", and then hangs. Why is that?
#include <iostream>
bool is_prime(int num)
{
if(num == 1)
{
return false;
}
for(int i = 2; i < num; i++)
{
if(num % i == 0)
{
return false;
}
}
return true;
}
int increase(int i)
{
return i++;
}
int main()
{
std::cout << "hello world!!" << std::endl;
int i = 1;
while(i < 100)
{
i = increase(i);
if(is_prime(i))
{
std::cout << i << " is prime" << std::endl;
}
}
}
return i++; this statement would return the original value of i, not the incremented one.
You need return ++i; or return i + 1 (thanks to #interjay for pointing that). The later return i + 1; makes it clear that only the return value matters, and not the new value of i.
The effect of post increment i++ would be visible on the next line (or usage of i).
Not really sure, if you need a separate method for incrementing your variable i, you can do that at in your while loop.
while(i < 100)
{
if(is_prime(i))
{
std::cout << i << " is prime" << std::endl;
}
i++;
}
You can also use a for loop, instead of while since you are working with a range of values.
for(i = 1; i < 100; i++)
{
if(is_prime(i))
{
std::cout << i << " is prime" << std::endl;
}
}
Try this:
int increase(int i)
{
return ++i;
}
to get the incremented value of i else you will get the original value of i which will lead you to infinite loop.
The better approach would be to use(for clarity):
int increase(int i)
{
return i+1;
}
You are calling i++. i++ remembers what value i had and returns that. Try to call ++i.
return i++; returns i then increase i in function stack,
use return ++i; instead.
remember doing something on X++ first do something then increase X.
the problem is that ur increase function keeps returning 1. To fix the issue, change i++ to ++i, the second one modify i by adding 1 before returning
why create a function to increase i. just i = i+1;
The problem is with i++; should be change to ++i;
i++ evaluates i and then increments i, whereas it should be increment i before you evaluate..
Another problem start from 5 instead of 2 since you already handled the case
bool is_prime(int num)
{
if(num == 1)
{
return false;
}
if(num == 2 || num == 3)
{
return true;
}
for(int i = 5; i < num; i++)
{
if(num % i == 0)
{
return false;
}
}
return true;
}
Another way of doing prime numbers:
bool is_prime(int num)
{
while(1)
{
int div = x-1;
if(x%div==0)
return false;
else
if(div != 1)
div--;
else
return false;
}
}
I++ increments I after executing the line. ++I increments I before executing the line.
You may check operator precedence (it works for c++ also)
c operator precedence
Note 2 explains why return I++ does not work.