Why does one star get pushed back when I enter a word into my square [closed] - c++

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 yesterday.
Improve this question
The program below executes a drawing of a square with the words hello world written in it. The problem is that after the word the star(makes the square) is pushed forward beyond all other stars. How can I push that star back with the others?
#include <iostream>
void Square();
int main()
{
Square();
}
void Square()
{
for (int i = 0; i < 25; i++)
{
for (int k = 0; k < 25; k++)
{
if (i == 0 || k == 0 || i ==24 || k == 24)
{
std::cout << "*";
}
else
{
std::cout << " ";
}
if (i == 8 && k == 5)
{
std::cout << "Hello World";
}
}
std::cout << std::endl;
}
}

The problem is that the else statement of the first is statement
if (i == 0 || k == 0 || i ==24 || k == 24)
{
std::cout << "*";
}
else
{
std::cout << " ";
}
always gets the control when the condition of the if statement evaluates to false before and after the next if statement
if (i == 8 && k == 5)
{
std::cout << "Hello World";
}
in turn gets the control. And the length of the string "Hello World" is ignored.
Actually there is no need to use nested for loops. It is enough to use only one for loop and stream manipulators.
Here is a demonstration program.
#include <iostream>
#include <iomanip>
std::ostream & Square( std::ostream &os = std::cout )
{
const char s[] = "Hello World";
const size_t length = sizeof( s ) - 1;
const size_t N = 25;
const size_t left_indent = ( N - length ) / 2;
const size_t right_indent = N - length - left_indent;
for (size_t i = 0; i < N; i++)
{
if (i == 0 || i == N - 1)
{
os << std::setw( N ) << std::setfill( '*' ) << '*' << '\n';
}
else if (i == 8)
{
std::cout << '*' << std::setw( left_indent - 1 + length ) << s
<< std::setw( right_indent ) << '*' << '\n';;
}
else
{
os << '*' << std::setw( N - 1 ) << std::setfill( ' ' ) << '*' << '\n';
}
}
return os;
}
int main()
{
Square() << '\n';
}
The program output is
*************************
* *
* *
* *
* *
* *
* *
* *
* Hello World *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
*************************
Another approach is to use formatting features declared in the header <format> provided that your compiler supports C++ 20.

Related

C++ asterisk loop program with space [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 6 years ago.
Improve this question
I wanted to make:
*
* *
* * *
* * * *
* * * * *
* * * * * *
but I don't know how to make the spacing, the closest I can get is by using:
#include <iostream>
#include <conio.h>
using namespace std;
int main(int argc, char** argv) {
int x, y;
for (y = 0 ; y <= 5 ; y ++){
for (x = 0 ; x < y ; x++) {
cout<<" * ";
}
printf("\n");
}
getch ();
return 0;
}
I'll help you.. but just because it's almost Christmas
int x, y;
for (y = 0; y <= 5; y++) {
for (x = 0; x < y; x++) {
for (int i = 0; x == 0 && i < (5 - y); ++i)
cout << ' ';
cout << " *";
}
cout << '\n';
}
Example
You start with 6 spaces and an asterix.
Next is 5 spaces and an asterix, followed by 1 space+asterix
Next is 4 spaces and an asterix, followed by 2 space+asterix
... and so on. Do you see the pattern?
#include <iostream>
int main(int argc, char* argv[])
{
for (int height = 6; height > 0; --height)
{
// Leading spaces
for (int i = 1; i < height; ++i)
{
std::cout << ' ';
}
// and the asterix
std::cout << '*';
// then trailing space+asterix
for (int i = height; i < 6; ++i)
{
std::cout << " *";
}
std::cout << std::endl;
}
}
Just output one space after the outputted asterisk
Here you are.
#include <iostream>
#include <iomanip>
int main()
{
while (true)
{
const char asterisk = '*';
std::cout << "Enter a non-negative number (0 - exit): ";
unsigned int n;
if (not (std::cin >> n) or n == 0) break;
std::cout << '\n';
for ( unsigned int i = 0; i < n; i++ )
{
std::cout << std::setw( n - i + 1 );
for (unsigned int j = 0; j < i + 1; j++)
{
std::cout << asterisk << (j == i ? '\n' : ' ');
}
}
std::cout << std::endl;
}
return 0;
}
The program output might look like
Enter a non-negative number (0 - exit): 6
*
* *
* * *
* * * *
* * * * *
* * * * * *
Enter a non-negative number (0 - exit): 5
*
* *
* * *
* * * *
* * * * *
Enter a non-negative number (0 - exit): 4
*
* *
* * *
* * * *
Enter a non-negative number (0 - exit): 3
*
* *
* * *
Enter a non-negative number (0 - exit): 2
*
* *
Enter a non-negative number (0 - exit): 1
*
Enter a non-negative number (0 - exit): 0

can I create a window in c++ using existing project code

I was wondering if i could create a window using my existing project code. This is a school project. However, I have completed the actual coding part and just wanted to make the project fancier, so to say. Thank you so much in advance for all the support.
Here is the actual code in case it would be of any help. It's a bit lengthy so be warned :) Once again, thank you in advance
#define NOMINMAX
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <windows.h>
#include <Windows.h>
#include <chrono>
#include <string>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int key[3][3];
double inverted[3][3];
int store[1][3] = { 0 };
int conv[666];
int random1()
{
unsigned long long int xRan;
srand(time(NULL));
xRan = rand() % 9999 + 1;
return xRan;
}
int random2()
{
unsigned long long int xRan;
xRan = rand() % 9999 + 1;
return xRan;
}
int random3()
{
int xRan;
xRan = rand() % 9999 + 1;
return xRan;
}
void clear_screen(char fill = ' ') {
COORD tl = { 0, 0 };
CONSOLE_SCREEN_BUFFER_INFO s;
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(console, &s);
DWORD written, cells = s.dwSize.X * s.dwSize.Y;
FillConsoleOutputCharacter(console, fill, cells, tl, &written);
FillConsoleOutputAttribute(console, s.wAttributes, cells, tl, &written);
SetConsoleCursorPosition(console, tl);
}
int convert(char letter) {
int conv;
conv = (int)letter;
return conv;
}
void reverseMult(double inv[3][3], int decode[1][3])
{
store[0][0] = decode[0][0] * inv[0][0] + decode[0][1] * inv[1][0] + decode[0][2] * inv[2][0] + 0.5;
store[0][1] = decode[0][0] * inv[0][1] + decode[0][1] * inv[1][1] + decode[0][2] * inv[2][1] + 0.5;
store[0][2] = decode[0][0] * inv[0][2] + decode[0][1] * inv[1][2] + decode[0][2] * inv[2][2] + 0.5;
}
void matrixMult(int q, int w, int e, int a[3][3])
{
int A[1][3] = { q, w, e };
int B[3][3] = {
{ a[0][0], a[0][1], a[0][2] },
{ a[1][0], a[1][1], a[1][2] },
{ a[2][0], a[2][1], a[2][2] }
};
store[0][0] = A[0][0] * B[0][0] + A[0][1] * B[1][0] + A[0][2] * B[2][0];
store[0][1] = A[0][0] * B[0][1] + A[0][1] * B[1][1] + A[0][2] * B[2][1];
store[0][2] = A[0][0] * B[0][2] + A[0][1] * B[1][2] + A[0][2] * B[2][2];
//cout << store[0][0] << endl << store[0][1] << endl << store[0][2] << endl << endl;
}
char reverseConv(int x){
char conv;
conv = (char)x;
return conv;
}
void inverse(int key[3][3], double det){
int cofactor[3][3] = {
{ (key[1][1] * key[2][2] - key[1][2] * key[2][1]), -(key[1][0] * key[2][2] - key[1][2] * key[2][0]), (key[1][0] * key[2][1] - key[1][1] * key[2][0]) },
{ -(key[0][1] * key[2][2] - key[0][2] * key[2][1]), (key[0][0] * key[2][2] - key[0][2] * key[2][0]), -(key[0][0] * key[2][1] - key[0][1] * key[2][0]) },
{ (key[0][1] * key[1][2] - key[0][2] * key[1][1]), -(key[0][0] * key[1][2] - key[0][2] * key[1][0]), (key[0][0] * key[1][1] - key[0][1] * key[1][0]) }
};
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
inverted[i][j] =det * cofactor[i][j];
}
}
}
int main()
{
while (1){
cout << "Would you like to encrypt or decrypt?(e/d)\n " << endl;
string ende;
cin >> ende;
clear_screen();
if (ende == "e")
{
cout << "Please enter a name for the message: " << endl << endl;
string file;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
getline(cin, file);
clear_screen();
file += ".txt";
ofstream encrypt;
encrypt.open(file);
string message;
cout << "Please enter the message you would like to encrypt: " << endl << endl;
//cin.ignore(numeric_limits<streamsize>::max(), '\n'); --- Not needed anymore, uncomment if you cannot input message
getline(cin, message);
if (message.length() % 3 != 0)
message += ' ';
if (message.length() % 3 != 0)
message += ' ';
clear_screen();
for (int i = 0; i < message.length(); ++i)
{
conv[i] = convert(message[i]);
}
int det = 0;
while (1){
key[0][0] = random1(); //1
key[0][1] = random2(); //2
key[0][2] = random3(); //3
key[1][0] = random1() * 13 / 7; //4
key[1][1] = random2() * 23 / 7; //5
key[1][2] = random3() * 33 / 7; //6
key[2][0] = random1() * 18 / 15; //7
key[2][1] = random2() * 18 / 12; //8
key[2][2] = random3() * 18 / 10; //9
det = key[0][0] * key[1][1] * key[2][2] + key[0][1] * key[1][2] * key[2][0] + key[0][2] * key[1][0] * key[2][1]
- key[0][2] * key[1][1] * key[2][0] - key[0][0] * key[1][2] * key[2][1] - key[0][1] * key[1][0] * key[2][2];
if (det != 0)
break;
}
encrypt << key[0][0] << ' ' << key[0][1] << ' ' << key[0][2] << ' '
<< key[1][0] << ' ' << key[1][1] << ' ' << key[1][2] << ' '
<< key[2][0] << ' ' << key[2][1] << ' ' << key[2][2] << endl << endl;
int a, b, c;
int count = 0;
for (int i = 0; i < (message.length)() / 3; ++i)
{
int counting = 0;
a = conv[count];
count++;
b = conv[count];
count++;
c = conv[count];
count++;
matrixMult(a, b, c, key);
encrypt << store[0][counting] << ' ';
counting++;
encrypt << store[0][counting] << ' ';
counting++;
encrypt << store[0][counting] << endl;
}
encrypt.close();
Sleep(750);
cout << "Your message has been encrypted." << endl;
Sleep(750);
cout << "Please check " << file << " for the encrypted message and key" << endl << endl;
Sleep(750);
}
if (ende == "d")
{
cout << "Please enter the name of the file you would like to decrypt: " << endl << endl;
string file;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
getline(cin, file);
clear_screen();
file += ".txt";
ifstream decrypt;
decrypt.open(file);
int key[3][3];
for (int i = 0; i < 3; ++i)
{
for (int k = 0; k < 3; ++k){
decrypt >> key[k][i];
}
}
int det = 0;
det = key[0][0] * key[1][1] * key[2][2] + key[0][1] * key[1][2] * key[2][0] + key[0][2] * key[1][0] * key[2][1] - key[0][2] * key[1][1] * key[2][0] - key[0][0] * key[1][2] * key[2][1] - key[0][1] * key[1][0] * key[2][2];
double detInv = 1;
detInv /= det;
//double inv;
inverse(key, detInv);
int out[1][3];
int count = 0;
while (!decrypt.eof()){
for (int i = 0; i < 3; ++i)
{
decrypt >> out[0][i];
}
reverseMult(inverted, out);
count++;
char a, b, c;
a = reverseConv(store[0][0]);
b = reverseConv(store[0][1]);
c = reverseConv(store[0][2]);
if (decrypt.eof())
break;
cout << a << b << c;
}
}
cout << endl << endl;
cout << "Would you like to continue?(y/n) ";
char again;
cin >> again;
if (again != 'y')
exit(0);
clear_screen();
}
return 0;
}
Yes, you can convert your project to a Windowing application. You have two choices:
Use Windows (native) API
Use graphics framework
Windows API
The Windows API is the direct method for creating windows. However, it is a lot of code, lots of chances for defects to be injected. It is a good learning experience about how the Windowing system works. Get Petzold's book.
GUI Framework
There are a lot of GUI frameworks out there. These C++ frameworks have simplified the GUI and Widget creation, using object oriented programming. There are many out there, so search the internet for "GUI Framework C++ review".
A Different Programming Perspective
In your present project, the OS executes the program and statements are executed in order. A windowing system is based on event driven programming. In summary, your GUI is waiting for an event to occur.
A simple example for your project is a window with a single button. When the User clicks on the button, the Windowing system sends a message to the button event handler. The event handler is a function that will execute your code.
As Thomas said, yes you can migrate your code to a Windows application, by either going native with Win32 or by either using a C++ GUI Framework (QT, wxWindows, ...).
However, you will need to invest time to learn one of the solution. I would suggest to learn a C++ Framework, programming with low-level Win32 api is not very used today.
Although it's off-topic, I would suggest some improvements to your code.
First, you shouldn't use goto, and replace them by a while. You can replace
again:
xRan = rand() % 9999 + 1;
if (xRan <1)
goto again;
By
do{
xRan = rand() % 9999 + 1;
} while (xRan < 1);
Note that in this case, a goto or a while is useless as xRan will always be superior or equal to 1 (rand() always returns a positive value)
Also you can replace convert and reverseConv very long functions by a constant array of struct values (struct contains a int and a const char*). convert and reverseConvert functions would only parse the array to find a proper match.

Strange output when using atof(optarg)

Edit::
Resolved- This was due to a misunderstanding of the use of the getOpt function.
I referenced the materials in the man here, on stack overflow (http://linux.die.net/man/3/getopt) and the getOpt documentation on GNU's website here: gnu.org/software/libc/manual/html_node/Example-of-Getopt.html Thanks to Bill Lynch and Remyabel for referencing source materials previously mentioned.
there seems to be an issue when I run this program using the -f variable to run the "Football" Commands, alongside using -c, However, I'm primarily concerned on getting just one to work for now.
Placing in the input:
-f -p 16 -a 25 -y 267 -t 1 -i 2
Gives out::
pC = 0
pC = 32738
pY = -1052776240
T = 32738
I = 1
Now, these variables should just be spitting out exactly what I put in, as the only conversion I'm using ( as seen below) is X = atof(optarg);
I suspect this may have something to do with the ASCII values, though I'm almost entirely clueless.
#
#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <time.h>
#include <stdlib.h>
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
double r = (6 + ( std::rand() % ( 8 - 6 + 1 ) )) / 10;
int c;
int pA;
int pY;
int T;
int I;
int pC;
double mass;
double bMass;
double dist;
double velo;
double Cr = .001;
double k = .18;
double g = 9.8;
double CFdraft;
double Pair;
double Proll;
double Psec;
double timeTravel = 0.0;
double Et;
double E;
double Eavg = 0;
int x = 0;
double cT;
double cC;
double cY;
double cI;
double PasserRating;
while ((c = getopt (argc, argv, "c:m:b:v:d:f:p:a:y:t:i:")) != -1)
{
if (c == 'f') // There seems to be some kind of misunderstanding with what this is doing
// The c=='f' line is there to designate which set of calculations to run, so, that needs to be the //foremost variable to be checked at the beginning of the program.
{
if (c == 'p')
{
pC = atof(optarg);
}
if (c == 'a')
{
pA = atof(optarg);
}
if (c == 'y')
{
pY = atof(optarg);
}
if (c == 't')
{
T = atof(optarg);
}
if (c == 'i')
{
I = atof(optarg);
}
cout << "pC " << pC << endl;
cout << "pC " << pA << endl;
cout << "pY " << pY << endl;
cout << "T " << T << endl;
cout << "I " << I << endl;
//Calculations
cC = ((pC / pA) - 0 / 30) * 5;
cY = ((pY / pA) - 3) * 0.25;
cT = ((T / pA) * 20);
cI = ((2.375) - (I / pA) * 25);
if (cC <= 0)
{
cC = 0;
}
if (cC >= 2.375)
{
cC = 2.375;
}
if (cY <= 0)
{
cY = 0;
}
if (cY >= 2.375)
{
cY = 2.375;
}
if (cT <= 0)
{
cT = 0;
}
if (cT >= 2.375)
{
cT = 2.375;
}
if (cI <= 0)
{
cI = 0;
}
if (cI >= 2.375)
{
cI = 2.375;
}
PasserRating = (((cC + cY + cT + cI) / 6) * 100);
string strPR = "Poor";
if (PasserRating <= 85)
{
strPR = "poor";
}
if (PasserRating > 85)
{
strPR = "mediocre";
}
if (PasserRating > 90)
{
strPR = "good ";
}
if (PasserRating > 95)
{
strPR = "great ";
}
cout << strPR << " " << PasserRating << endl;
}
if (c == 'c')
{
if (c == 'm')
{
mass = atof(optarg);
}
if (c == 'b')
{
bMass = atof(optarg);
}
if (c == 'd')
{
dist = atof(optarg);
}
if (c == 'v')
{
velo = atof(optarg);
}
timeTravel = (dist * 1000) / velo;
cout << "time:" << timeTravel << endl;
cout << "mass " << mass << endl;
cout << "bMass " << bMass << endl;
cout << "dist " << dist << endl;
cout << "velo " << velo << endl;
for (x = 0; x < (10); x ++)
{
CFdraft = r;
Pair = k * CFdraft * (pow(velo, 3));
Proll = Cr * g * (mass + bMass) * velo;
Psec = Pair + Proll;
Et = (Psec * timeTravel);
E = E + Et;
Eavg = E / timeTravel;
}
cout << Eavg << " KJ" << endl;
}
}
return 0;
}
I seriously recommend properly indenting your code. If you did, you would see this:
if(c == 'f'){
if (c == 'p')
...
}
Clearly c is not going to be equal to 'f' and 'p' at the same time.
You never execute your parsing code - everything is inside if(c == 'f') condition, which is obviously true only for the first time you run the loop... So you just get random values from the memory.

Outputting a Square Shape C++ using '*'

Hello I am very new to programming and my assignment is to output shapes. The first is the square:
int main(){
unsigned size;
cout <<"Size: ? ";
cin >>size;
for ( unsigned r = 0; r < size; r++ ){ // Square
for ( unsigned c = 0; c < size ; c++ )
if ( r == c )
cout <<'*';
cout <<endl;
}
cout <<endl;
}
When I input "5" after being prompted. The output results in:
5
*
*
*
*
*
Can anyone explain what is wrong with my code? I need to have both horizontal and vertical outputs. Thank you
You are only outputting a * on the diagonal, when r is the same as c. And you output nothing else but some endlines, so you end up with just a single star on each line.
#include <iostream>
using namespace std;
int main(){
unsigned size;
bool solid = true; //solid or hollow shape?
cout <<"Size: ? ";
cin >>size;
size = 5;
cout << endl;
for ( unsigned r = 0; r < size; r++ ){ // Square
for ( unsigned c = 0; c < size ; c++ ){
if(solid){
cout << " * ";
}
else{
if(r == 0 || r == size-1 || c == 0 or c == size-1){
cout << " * ";
}
else{
cout << " ";
}
}
}
cout <<endl;
}
cout <<endl;
}
Output Hollow:
* * * * *
* *
* *
* *
* * * * *
Solid:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
Only time the * is printed is when r == c. What's the purpose of the if statement?
Try commenting the if statement and see the result.

class variable access within recursive function

for an intro program, we were asked to build a program that could find every single possible working magic square of a given size. I am having trouble modifying a class variable from within a recursive function. I am trying to increment the number of magic squares found every time the combination of numbers I am trying yields a magic square.
More specifically, I am trying to modify numSquares within the function recursiveMagic(). After setting a breakpoint at that specific line, the variable, numSquares does not change, even though I am incrementing it. I think it has something to do with the recursion, however, I am not sure. If you want to lend some advice, I appreciate it.
//============================================================================
// Name : magicSquare.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
/**
* MagicSquare
*/
class MagicSquare {
private:
int magicSquare[9];
int usedNumbers[9];
int numSquares;
int N;
int magicInt;
public:
MagicSquare() {
numSquares = 0;
for (int i = 0; i < 9; i++)
usedNumbers[i] = 0;
N = 3; //default is 3
magicInt = N * (N * N + 1) / 2;
}
MagicSquare(int n) {
numSquares = 0;
for (int i = 0; i < 9; i++)
usedNumbers[i] = 0;
N = n;
magicInt = N * (N * N + 1) / 2;
}
void recursiveMagic(int n) {
for (int i = 1; i <= N * N + 1; i++) {
if (usedNumbers[i - 1] == 0) {
usedNumbers[i - 1] = 1;
magicSquare[n] = i;
if (n < N * N)
recursiveMagic(n + 1);
else {
if (isMagicSquare()) {
numSquares++; //this is the line that is not working correctly
printSquare();
}
}
usedNumbers[i - 1] = 0;
}
}
}
//To efficiently check all rows and collumns, we must convert the one dimensional array into a 2d array
//since the sudo 2d array looks like this:
// 0 1 2
// 3 4 5
// 6 7 8
//the following for-if loops convert the i to the appropriate location.
bool isMagicSquare() {
for (int i = 0; i < 3; i++) {
if ((magicSquare[i * 3] + magicSquare[i * 3 + 1] + magicSquare[i * 3 + 2]) != magicInt) //check horizontal
return false;
else if ((magicSquare[i] + magicSquare[i + 3] + magicSquare[i + 6]) != magicInt) // check vertical
return false;
}
if ((magicSquare[0] + magicSquare[4] + magicSquare[8]) != magicInt)
return false;
if ((magicSquare[6] + magicSquare[4] + magicSquare[2]) != magicInt)
return false;
return true;
}
/**
* printSquare: prints the current magic square combination
*/
void printSquare() {
for (int i = 0; i < 3; i++)
cout << magicSquare[i * 3] << " " << magicSquare[i * 3 + 1]
<< " " << magicSquare[i * 3 + 2] << endl;
cout << "------------------" << endl;
}
/**
* checkRow: checks to see if the current row will complete the magic square
* #param i - used to determine what row is being analyzed
* #return true if it is a working row, and false if it is not
*/
bool checkRow(int i) {
i = (i + 1) % 3 - 1;
return (magicSquare[i * 3] + magicSquare[i * 3 + 1] + magicSquare[i * 3 + 2]) == magicInt;
}
int getnumSquares() {
return numSquares;
}
}; //------End of MagicSquare Class-----
int main() {
MagicSquare square;
cout << "Begin Magic Square recursion:" << endl << "------------------"
<< endl;
square.recursiveMagic(0);
cout << "Done with routine, returned combinations: " << square.getnumSquares() << endl;
return 0;
}
The array is being overwritten leading to overwriting the numSquares field.
class MagicSquare {
private:
int magicSquare[9];
int usedNumbers[9];
Changes to
class MagicSquare {
private:
int magicSquare[10];
int usedNumbers[10];
Also in your initializer the loop says < 9 but what you want to say is < 10. Or just use memset is better for that purpose.