Why are my grater than and less than if statements not working? - visual-c++

The beginning of my code
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "give two values: ";
int val1 = 0;
int val2 = 0;
int low = 0;
int high = 0;
The section below (up to the break) should differentiate between the highest and
Lowest values for val1 and val2, but Val2 always equals high, and val1
always equals low when I run the program. It seems that the greater than and less that if statements that I have created are not working.
while (cin >> val1 >> val2) {
if (val1 == val2) {
cout << "the values are equal\n";
high = val1;
low = val2 ;
}
if (val1 > val2) {
high = val1;
low = val2;
}
else if (val1 < val2); {
high = val2;
low = val1;
}
break;
}
This is the last part of my code and it gives the user info about the numbers
they picked
cout << "Value one and two added together is: " << val1 + val2 << "\n"
<< "Value one and two subtracted is: " << val1 - val2 << "\n"
<< "value one and two multiplyed is: " << val1*val2 << "\n"
<< "value one and two divided is: " << val1 / val2 << "\n"
<< "The lowest value is:" << low << " and the highest value is:" << high;
return 0;
}

Related

Why cout<<"Hello world" + 10; prints d in the output [duplicate]

The code successfully compiles it but I can't understand why, for certain values of number, the program crashes and for other values it doesn't. Could someone explain the behavior of adding a long int with a char* that the compiler uses?
#include <iostream>
int main()
{
long int number=255;
std::cout<< "Value 1 : " << std::flush << ("" + number) << std::flush << std::endl;
number=15155;
std::cout<< "Value 2 : " << std::flush << ("" + number) << std::flush << std::endl;
return 0;
}
Test results:
Value 1 : >
Value 2 : Segmentation fault
Note: I'm not looking for a solution on how to add a string with a number.
In C++, "" is a const char[1] array, which decays into a const char* pointer to the first element of the array (in this case, the string literal's '\0' nul terminator).
Adding an integer to a pointer performs pointer arithmetic, which will advance the memory address in the pointer by the specified number of elements of the type the pointer is declared as (in this case, char).
So, in your example, ... << ("" + number) << ... is equivalent to ... << &""[number] << ..., or more generically:
const char *ptr = &""[0];
ptr = reinterpret_cast<const char*>(
reinterpret_cast<const uintptr_t>(ptr)
+ (number * sizeof(char))
);
... << ptr << ...
Which means you are going out of bounds of the array when number is any value other than 0, thus your code has undefined behavior and anything could happen when operator<< tries to dereference the invalid pointer you give it.
Unlike in many scripting languages, ("" + number) is not the correct way to convert an integer to a string in C++. You need to use an explicit conversion function instead, such as std::to_string(), eg:
#include <iostream>
#include <string>
int main()
{
long int number = 255;
std::cout << "Value 1 : " << std::flush << std::to_string(number) << std::flush << std::endl;
number = 15155;
std::cout << "Value 2 : " << std::flush << std::to_string(number) << std::flush << std::endl;
return 0;
}
Or, you can simply let std::ostream::operator<< handle that conversion for you, eg:
#include <iostream>
int main()
{
long int number = 255;
std::cout<< "Value 1 : " << std::flush << number << std::flush << std::endl;
number = 15155;
std::cout<< "Value 2 : " << std::flush << number << std::flush << std::endl;
return 0;
}
Pointer arithmetic is the culprit.
A const char* is accepted by operator<<, but will not point to a valid memory address in your example.
If you switch on -Wall, you will see a compiler warning about that:
main.cpp: In function 'int main()':
main.cpp:6:59: warning: array subscript 255 is outside array bounds of 'const char [1]' [-Warray-bounds]
6 | std::cout<< "Value 1 : " << std::flush << ("" + number) << std::flush << std::endl;
| ^
main.cpp:8:59: warning: array subscript 15155 is outside array bounds of 'const char [1]' [-Warray-bounds]
8 | std::cout<< "Value 2 : " << std::flush << ("" + number) << std::flush << std::endl;
| ^
Value 1 : q
Live Demo

My code is stuck in an infinite loop in C++

I am trying to use a while loop to calculate the average of 3 inputted grades, but I can not enter the next grade as the loops keep on going without giving me the chance to enter the next grade.
#include<iostream>
using namespace std;
int main()
{
int grade = 0;
int count = 0;
int total = 0;
cout << "Enter grade: ";
cin >> grade;
while (grade != -1)
{
total = total + grade;
count = count + 1;
cout << "Enter next grade: ";
cin >> grade;
}
int(average) = total / 3;
cout << "Average: " << int(average) << endl;
system("pause");
}
I tested your code with integer and it works fine.
If you only take int as input, the best is to put something to check the input type. Use cin.fail() to check if user input anything other than int.
for example:
while(cin.fail()) {
cout << "Error" << endl;
cin.clear();
cin.ignore(256,'\n');
cout << "Please enter grade:"
std::cin >> grade;
}
which I refer from https://www.codegrepper.com/code-examples/cpp/how+to+check+type+of+input+cin+c%2B%2B
and here as well Checking cin input stream produces an integer

I'm trying to make a loop to draw multiple lines in cairo but it stops drawing after the first iteration

I'm making a program where a person can input a direction and in the if statement, it adds/subtracts x/y axis and it draws a line after it gets over. The problem is that for some reason, it only works at the first iteration and doesn't draw any more lines after that.
I added a cin >> x >> y to test it out but it only draws one line and doesn't draw anymore.
Initially, the choices were in a switch statement but I changed to if because I thought that was causing the error.
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string.h>
#include <cairo.h>
#define _USE_MATH_DEFINES
#include <math.h>
using namespace std;
char b = NULL;
char u = 'œ';
char d = 'd';
int main()
{
cairo_surface_t *surface = cairo_image_surface_create_from_png("background.png");
cairo_t *cr = cairo_create(surface);
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_set_line_width(cr, 5);
double x = 0, y = 240;
cairo_move_to(cr, x, y);
long int count = 0;
int cl = 0;
int crr = 0;
int choice = 0;
int n;
system("cls");
while (choice != 5)
{
cin >> x >> y;
cairo_line_to(cr, x, y);
cairo_stroke(cr);
cairo_surface_write_to_png(surface, "spiral.png");
cout << "Current no. of points are : " << count << "/4096" << endl;
cout << "Enter direction: \n" << endl;
cout << "1 - Top Left \t 2 - Up \t 3 - Top Right " << endl;
cout << "4 - Left \t 5 - Stop \t 6 - Right" << endl;
cout << "7 - Bot. Left \t 8 - Down \t 9 - Bot. Right" << endl << endl;
cout << "Enter you choice: ";
cin >> choice;
if (choice == 1)
cout << "Test";
else
{
//More choices include the direction the person needs to go and it subtracts/adds to the x/y part
cout << "How many times ?: ";
cin >> n;
for (int i = 1; i <= n; i++)
{
x++;
count++;
cl++;
if (cl == 256)
{
cl = 0;
crr++;
}
}
system("cls");
}
}
}
I expect it to draw lines to a particular direction. Say the person inputs right, it draws a line towards right and so on. But here, no lines get drawn at all (except if I add a cin >> x >> y at the start of the while loop, that draws one line and that's it, no more lines.)
This fails because there is no current point anymore. After cairo_stroke(cr);, you can add cairo_move_to(cr, x, y); and it should start drawing more lines in the way you expect. I think... I'm not quite sure what you are up to with this program.

Do while loop won't break

I am making a Goldilocks game. If the user chooses the wrong answer it would loop back to the beginning of the program. When I try to choose any option it always loops back to the beginning including the correct answer which is 2. I am still new to c++. I do not understand why it is looping to the beginning if the condition is true when 2 is chosen.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void FirstSet()
{
bool win = false;
string PName;
int choice;
int num1, num2, result;
do
{
system("CLS");
cout << " Please Enter Name \n";
cin >> PName;
cout << PName << " and the Three Bears\n\n ";
cout << PName << " Walks up and sees 3 Doors, 1 Large Door, 1 Medium
Door and 1 Small Door. \n\n\n " << "Which Door do you want to Open?\n "
<< " 1 for The Large Door\n " << " 2 for the Medium Door\n " << " 3
for the small door\n ";
cin >> choice;
if (choice == '1')
{
cout << " The large door is too heavy it will not budge.\n "
<< " Please Try Again\n\n ";
system("pause");
}
else if (choice == '2')
{
win = true;
}
else if (choice == '3') {
cout << " The Door is too small you would get stuck.\n "
<< "Please Try Again\n\n";
}
} while (!win);
}
int main()
{
FirstSet();
system("pause");
return 0;`
The reason none of your comparisons are turning true is because you are reading the input into an int variable. Then you are comparing to ascii character values of 1,2 and 3 which happen to be 49, 50 and 51 respectively. If you modify your if lines to compare directly with integers, it should work:
if (choice == 1)
{
...
}
else if (choice == 2)
{
...
}
else if (choice == 3)
{
...
}
Although, for readability purposes and also to avoid such cases, I recommend using switch case statements in this case.

Why VS 2015 is giving me the exception at the end of the code below?

I am somewhat new to c++, our class only went over debugging briefly. This is probably my 10th do over, I have been over it a week, have done plenty of research over the web and I just don't understand debugging enough to figure out how to fix my code. The program is supposed to real a file like this:
TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF
When it reads the file it's supposed to output the student ids, what they answered on each question and the grade for each student. My problem is, I don't know much about debugging and VS keeps throwing an exception at the end of the code I provided. I am just learning how to use dynamic arrays so I know it has something to do with my use of them because I had the program working fine in my other c++ class but I had to change it around to use dynamic arrays for this project.
What's wrong with my program? I have researched the web and reread the chapters in the book over and over and I cannot figure it out.
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <cstddef>
using namespace std;
// function prototypes
void readFile(ifstream& inFile);
char assignGrade(int score, int numQues);
int main()
{
int numQues = 20;
int numStud = 0;
string *studentIDs;
studentIDs = new string[numStud];
char *correctAnswers;
correctAnswers = new char[numStud];
char *studentAnswers;
studentAnswers = new char[numQues];
ifstream inFile;
cout << "\nRedo Programming Exercise Six of Chapter Eight\nUsing Dynamic Arrays..." << endl;
cout << "\nPlease Enter the Number of Students: ";
cin >> numStud;
cout << endl;
readFile(inFile);
inFile.getline(correctAnswers, '/n'); // read the correct answers first
for (int i = 0; i < numStud; i++) // loop students
{
inFile >> studentIDs[i]; // get the student ID
inFile.get(); // discard the space between the student ID and the answer
for (int j = 0; j < numQues; j++) // loop questions
{
studentAnswers[j] = inFile.get(); // get the student's answers
}// end for
cout << "Student ID: " << studentIDs[i] << endl; // output student id
int score = 0; // declare and initialize score to zero
cout << "Answers: "; // display "Answers: "
for (int j = 0; j < numQues; j++) // loop each question
{
cout << studentAnswers[j]; // output student's answers
if (studentAnswers[j] == correctAnswers[j]) // if student answer equals correct answer
score += 2; // correct answer
else if (studentAnswers[j] != correctAnswers[j] && studentAnswers[j] != ' ')
score -= 1; // incorrect answer but not a blank
else if (studentAnswers[j] == ' ')
score = 0;
delete[] studentAnswers;
}// end for
if (score < 0)
score = 0; // don't allow for negative scores
cout << endl; // new line, housekeeping
char grade = assignGrade(score, numQues); // call assignGrade function
cout << "Grade: " << grade << "\n" << endl; // display grade
}// end for
delete[] studentIDs;
system("pause");
return(0);
}
void readFile(ifstream& inFile)
{
inFile.open("Ch12_Ex2Data.txt"); // use inFile to open Ch8_Ex6Data.txt
if (!inFile) // if the file can't be opened or it is corrupt
{
cout << "There was an error opening the input file...\nPlease check file and try again!\n" << endl; // display error message
system("pause");
exit(1); // exit the program
}
} // end readFile function
char assignGrade(int score, int numQues)
{
double percentScore = static_cast<double>(score) / (numQues * 2); // calculate the score percentage
cout << "Score: " << percentScore * 100 << "%" << endl; // display the score
if (percentScore >= 0.9) // if score is greater than or equal to 90%, return A
return 'A';
else if (percentScore >= 0.8) // if score is greater than or equal to 80%, return B
return 'B';
else if (percentScore >= 0.7) // if score is greater than or equal to 70%, return C
return 'C';
else if (percentScore >= 0.6) // if score is greater than or equal to 60%, return D
return 'D';
else // any score lower thn 60%, return F
return 'F';
} // end assignGrade function
It keeps breaking here in the debugger:
static void __CLRCALL_OR_CDECL assign(_Elem& _Left, const _Elem& _Right)
_NOEXCEPT
{ // assign an element
_Left = _Right;
}
// Redo Programming Exercise Six of Chapter Eight
// Using Dynamic Arrays -- C++ Advanced
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// function prototype
void readFile(ifstream& inFile, string fileName);
int main()
{
// variables, pointers and dynamic arrays
int numStud = 200; // stores the number of students, max students was 200
int numQues = 20; // stores the number of questions on test
string *studentIDs; // pointer variable for studentIDs dynamic array
char *correctAnswers; // pointer variable for correctAnswers dynamic array
correctAnswers = new char[numQues]; // correctAnswers dynamic char array
char *studentAnswers; // pointer variable for studentAnswers dynamic array
studentAnswers = new char[numQues]; // studentAnswers dynamic char array
char *fileName; // pointer variable for fileName dynamic char array
fileName = new char[25]; // fileName dynamic char array
ifstream inFile; // input stream variable inFile
// display message to explain the program
cout << "\nJames Flowers - Chapter 12 - Programming Exercise 2" << endl;
cout << "\nRedo Programming Exercise Six of Chapter Eight\nUsing Dynamic Arrays..." << endl;
// request file name for fileName dynamic char array
cout << "\nPlease Enter the File Name (Ch12_Ex2Data.txt): ";
cin >> fileName;
cout << endl;
// call readFile function to read the file
readFile(inFile, fileName);
// request number of students for studentIDs dynamic char array and some calculations
cout << "\nHow many students took this test? (4): ";
cin >> numStud;
cout << endl;
studentIDs = new string[numStud]; // create studentIDs dynamic char array
inFile.getline(correctAnswers, '/n'); // read the correct answers first
for (int i = 0; i < numStud; i++) // loop students
{
inFile >> studentIDs[i]; // get the student ID
inFile.get(); // discard the blank space
inFile.getline(studentAnswers, '/n'); // get the student's test answers
cout << "Student ID: " << studentIDs[i] << endl; // output student id
int score = 0; // declare and initialize score to zero
cout << "Answers: "; // display "Answers: "
for (int j = 0; j < numQues; j++) // loop each question
{
cout << studentAnswers[j]; // output student's answers
if (studentAnswers[j] == correctAnswers[j]) // if student answer is correct
score += 2; // add 2 to score
else if (studentAnswers[j] != correctAnswers[j] && studentAnswers[j] != ' ') // incorrect answer but not blank
score -= 1; // subtract 1 from score
else if (studentAnswers[j] == ' ') // if question left blank
score -= 0; // nothing subtracted from score
studentAnswers[j] = ' '; // clear each indice for next student
}// end for
cout << endl; // new line, housekeeping
char grade = 0; // char variable grade initialized to 0
double percentScore = static_cast<double>(score) / (numQues * 2); // calculate the score percentage
cout << "Score: " << percentScore * 100 << "%" << endl; // display the score
if (percentScore >= 0.9) // if score is greater than or equal to 90%, return A
grade = 'A'; // grade = A
else if (percentScore >= 0.8) // if score is greater than or equal to 80%, return B
grade = 'B'; // grade = B
else if (percentScore >= 0.7) // if score is greater than or equal to 70%,
grade = 'C'; // grade = C
else if (percentScore >= 0.6) // if score is greater than or equal to 60%,
grade = 'D'; // grade = D
else // any score lower than 60%,
grade = 'F'; // grade = F
cout << "Grade: " << grade << "\n" << endl; // display grade
}// end for
system("pause"); // pause for readability
return(0);
}// end main
// readFile function reads the file, if not displays error message
void readFile(ifstream& inFile, string fileName)
{
inFile.open(fileName); // use inFile to open input file
if (!inFile.is_open()) // if the file can't be opened or it is corrupt
{
cout << "There was an error opening the input file...\nPlease check file name and try again!\n" << endl; // display error message
system("pause"); // pause for readability
exit(1);
}// end if
} // end readFile function

Resources