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
}
}
}
}
}
Related
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') {
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.
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();
}
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'm learning C++ and whilst I have a reasonable understanding of C# I've never run into this issue before. With a simple program that places chess pieces on an imaginary board (an enumerated array) and then assigns the squares which would have pieces at the start their pieces, you are then asked for coordinates and the program returns what is on that square. It displays the correct piece yet will always crash in non-debugging mode and display a buffer overrun in Visual Studio debugging. It's quite short so I'll show all the code.
#include <iostream>
#include <string>
using namespace std;
int main() {
enum Chessboard {
Blank,
Pawn,
Rook,
Knight,
Bishop,
King,
Queen
};
Chessboard board[8][8] = { Blank };
for (int x = 1; x < 8; x++)
{
board[1][x] = Pawn;
board[8][x] = Pawn;
}
board[7][0] = Rook;
board[7][1] = Knight;
board[7][2] = Bishop;
board[7][3] = King;
board[7][4] = Queen;
board[7][5] = Bishop;
board[7][6] = Knight;
board[7][7] = Rook;
board[0][0] = Rook;
board[0][1] = Knight;
board[0][2] = Bishop;
board[0][4] = King;
board[0][3] = Queen;
board[0][5] = Bishop;
board[0][6] = Knight;
board[0][7] = Rook;
int X = 0;
int Y = 0;
bool Error = false;
cout << "Enter the coordinates of a square on a chessboard to see what is on there at the start of the game (1 number at a time)" << endl;
do {
cin >> X;
X--;
Error = false;
if (X < 0 || X > 7)
{
cout << "That's not on the board" << endl;
Error = true;
}
} while (Error = false);
do {
cin >> Y;
Y--;
Error = false;
if (Y < 0 || Y > 7)
{
cout << "That's not on the board" << endl;
Error = true;
}
} while (Error = false);
string Name = "";
Chessboard Piece = board[X][Y];
switch (Piece)
{
case Blank: Name = "nothing";
break;
case Pawn: Name = "a Pawn";
break;
case Rook: Name = "a Rook";
break;
case Knight: Name = "a Knight";
break;
case Bishop: Name = "a Bishop";
break;
case King: Name = "a King";
break;
case Queen: Name = "a Queen";
break;
default: Name = "Somehow you missed the board";
break;
}
cout << "On " << ++X << "," << ++Y << " there is " << Name << endl;
return 0;
}
You'll certainly get an overrun here:
Chessboard board[8][8] = { Blank };
for (int x = 1; x < 8; x++)
{
board[1][x] = Pawn;
board[8][x] = Pawn;
}
There's no board[8][]. You have board[0][] through board[7][] available.
You are going outside the boundaries of your matrix
board[1][x] = Pawn;
board[8][x] = Pawn;
You declared it 8x8 so index 0..7 are to be used.
In C, C++ and C# indices of arrays start from 0 to size of the array - 1. So for example this loop
for (int x = 1; x < 8; x++)
{
board[1][x] = Pawn;
board[8][x] = Pawn;
}
has to be rewritten as
for ( int x = 0; x < 8; x++)
{
board[1][x] = Pawn;
board[6][x] = Pawn;
}
provided that the array is defined as
Chessboard board[8][8] = { Blank };
Also it would be a good idea to introduce a mnemonic name for magic number 8 and use this name everwhere instead of the number.
for (int x = 0; x < 8; x++)
{
board[0][x] = Pawn;
board[7][x] = Pawn;
}
I think 7 is the maximum for this array.
As stated by everybody else, its the board[8][x] = Pawn that is causing the error.
Though this appears to be a test program rather than something that will go into production but still one word of caution that I would like to advise, always try to avoid numbers / hard coded strings/integers or anything else, in your code for reason that you usually end up doing things like this. And one day when project goes into production and may be your boss will decide to change the value to say, 100 x 100, you will have a very hard time doing things.
Good Ways to do this :
static const int BoardSize = 10;
or
#define BoardSize 10;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm trying to write a C++ program that creates a list of letters that will
be used to encode a message according to the following rules:
Input a word
Remove all repeating letters to form the modified word
Place the modified word at the beginning of the array
Fill the remainder of the list with any letters of the alphabet that were not used in the word working from A to Z. (Your list should have all 26 letters of the alphabet)
For example, if the user enters HELLO, the modified word would become HELO, and the list would become HELOABCDFGIJKMNPQRSTUVXYZ. The list must be stored in an array of CHARacters.
This is the code I've written:
#include <iostream>
using namespace std;
int main()
{
char a;
int b = 0;
char word[4] = "\0";
char alphabet[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char code[27];
cout << "Please enter a word:" << endl;
cin >> word;
for (int i = 0; i<3; i++)
{
if (word[i] == word[i - 1])
{
a = word[i];
word[i] = word[i + 1];
}
code[i] = word[i];
b++;
}
for (int o = 0; o<27; o++)
{
if (alphabet[o] == word[1] || alphabet[o] == word[2] || alphabet[o] == word[3] || alphabet[o] == word[0])
{
o++;
}
code[b] = alphabet[o];
b++;
}
cout << code;
return 0;
}
Unfortunately, I'm getting this error:
Run-Time Check Failure #2
Stack around the variable word was corrupted.
Secondly, my code works for 4 characters. How can I make it work for any word?
this is a simple way to do this assignment.
note that input word lenght should be smaller than 100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char word[100]; // input word lenght should be smaller than 100
char used[26];
memset(used, 0, 26);
scanf("%s", word);
for (int i=0; i<strlen(word); i++)
{
// convert to uppercase
if (word[i]>='a' && word[i]<='z')
word[i] -= 'a'-'A';
// skip non-alphabetic characters
if (word[i]<'A' || word[i]>'Z')
continue;
// print this char only if it's not been printed before
if (!used[word[i]-'A'])
printf("%c", word[i]);
// set to 1 so that we don't print it again
used[word[i]-'A'] = 1;
}
// print all unused characters
for (int i=0; i<26; i++)
if (!used[i])
printf("%c", i+'A');
printf("\n");
return 0;
}