Visual Studio Appears to be ignoring my IF function - c++

I've been trying to practice small parts of my coding for an impending assignment but for the life of me I can't get visual studio to recognise that there's an if function, it just completely skips over it. The window closes as soon as I press enter.
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "Enter first number.";
cin >> a;
cout << "Enter second number.";
cin >> b;
if( a > b)
{
cout << "Variable a is greater than variable b." << endl;
cout << "Value of a is " << a << " value of b is " << b << endl;
}
return 0;
}

Not portable but, as you're using Visual Studio, you're on Windows, so it'll work. When you works in Debug mode, with Visual Studio, you don't need to add system("pause"), or something else, to your program. So I guess you're working in Release mode.
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "Enter first number.";
cin >> a;
cout << "Enter second number.";
cin >> b;
if( a > b)
{
cout << "Variable a is greater than variable b." << endl;
cout << "Value of a is " << a << " value of b is " << b << endl;
}
system("pause");
return 0;
}
EDIT :
You shouldn't use std::endl for a new line, or at least not each time you need a new line. You should just write << "\n"; std::endl insert a new line character + flushes the buffer. That's important to understand the difference between << std::endl; and << "\n";

Related

How do I restrict the user to number only inputs?

Ok, so basically I am having to make a basic program for a club at my school. I am trying to make it to where when the user inputs something that is not a number, it has an error message and loops back around to ask for the number again. This is not it exactly, but something I threw together real quick as an example.
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int a;
int b;
do{
cout << "Welcome to the equalizer. Please enter a number." << endl;
cin >> a;
cout << endl << "Ok, now I need another number." << endl;
cin >> b; //if a number is not entered, I need an error message and a loop back to the request for the number.
if(a>b){
cout << a << " is greater than " << b << endl;
}
if(b>a){
cout << b << " is greater than " << a << endl;
}
if(b=a){
cout << a << " is equal to " << b << endl;
}
cout << "restart? Enter Y if yes, or enter anything else to close." << endl;
cin >> c;
}while(c=="y" || c=="Y");
return 0;
Well, if I got it right, you can use something like "isdigit('char')". Do not forget to include "ctype.h".
In your code it will be something like:
if (!isdigit(c))
continue;
If the number may be a string like "1232321" then you may need to iterate through that string checking each char and exit if it is not...
bool error = false;
for (int i = 0; i < c.length(); i ++)
{
if (!isdigit(c[i]))
{
error = true;
break;
}
}
Hope, this helps.
P.S. Of course, "a" and "b" in your example should be of type string or char...

retrieving int value from void sub function to function in C++

I'm a foundation student who starting to learn coding C++. I'm doing a survey program for my college assignment and after the testing, i found out that the sum value from the sub function cannot sum up properly to the value in main function. any one HELP!!!
here is the code:
#include <iostream>
using namespace std;
int Q1();
int Q2();
int Q3();
int Q4();
int Q5();
int main()
{
char select;
int E, A, C, N, O;
int extroversion=0, agreeableness=0, conscientiousness=0, neuroticism=0, opennesstoexperience=0;
cout << "This is a Self-Esteem Questionnaire." << endl;
cout << "\nInsert S to start the test (Q to Quit): ";
cin >> select;
select=toupper(select);
if (select=='S')
{
cout << "------------------INSTRUCTIONS-----------------" << endl;
cout << "For each statement 1-50 mark how much you agree" << endl;
cout << "with on the scale 1-5, where " << endl;
cout << "1=disagree, 2=slightly disagree, 3=neutral, " << endl;
cout << "4=slightly agree and 5=agree " << endl;
cout << "-----------------------------------------------" << endl;
cout << Q1() << endl;
extroversion+=E;
cout << Q2() << endl;
agreeableness+=A;
cout << Q3() << endl;
conscientiousness+=C;
cout << Q4() << endl;
neuroticism+=N;
cout << Q5() << endl;
opennesstoexperience+=O;
cout << extroversion << endl;
cout << agreeableness << endl;
cout << conscientiousness << endl;
cout << neuroticism << endl;
cout << opennesstoexperience << endl;
}
else
if(select=='Q')
{
cout << "Program quit!" << endl;
}
return 0;
}
int Q1()
{
int E=0;
cout << "I am the life of the party." << endl;
cout << "1=disagree, 2=slightly disagree, 3=neutral," << endl;
cout << "4=slightly agree and 5=agree" << endl;
cout << "\nRating: ";
cin >> E;
return E;
}
int Q2()
{
int A=0;
cout << "I feel little concern for others." << endl;
cout << "1=disagree, 2=slightly disagree, 3=neutral," << endl;
cout << "4=slightly agree and 5=agree" << endl;
cout << "\nRating: ";
cin >> A;
return A;
}
int Q3()
{
int C=0;
cout << "I am always prepared." << endl;
cout << "1=disagree, 2=slightly disagree, 3=neutral," << endl;
cout << "4=slightly agree and 5=agree" << endl;
cout << "\nRating: ";
cin >> C;
return C;
}
int Q4()
{
int N=0;
cout << "I get stressed out easily." << endl;
cout << "1=disagree, 2=slightly disagree, 3=neutral," << endl;
cout << "4=slightly agree and 5=agree" << endl;
cout << "\nRating: ";
cin >> N;
return N;
}
int Q5()
{
int O=0;
cout << "I have a rich vocabulary." << endl;
cout << "1=disagree, 2=slightly disagree, 3=neutral," << endl;
cout << "4=slightly agree and 5=agree" << endl;
cout << "\nRating: ";
cin >> O;
return O;
}`
Let's start by reducing this problem to its essentials.
int main()
{
int E;
int extroversion=0;
cout << Q1() << endl;
extroversion+=E;
cout << extroversion << endl;
return 0;
}
int Q1()
{
int E=0;
cout << "Give me a number" << endl;
cin >> E;
return E;
}
The problem is that the variable E you have declared in Q1, has nothing to do with the variable E you have declared in main. Therefor when you write:
extroversion+=E;
you are using an uninitialized variable. The solution is to rewrite main as:
int main()
{
int extroversion=0;
int E = Q1(); // Capture the result of Q1 in E
cout << E << endl;// ... *then* print it.
extroversion+=E; // And now you can use the value of E in this function.
cout << extroversion << endl;
return 0;
}
Please note: That "reduced" problem is what you should have posted in the first place - we don't need to see the masses of text, and we certainly don't need to see you do the same thing five times. Remove the verbiage (and check that you still have the problem), and then post the reduced problem.
You're using a truck load of uninitialised variables in main. You are returning values back from the various Q functions, which are being used by the cout calls, but you are not setting E, A, C, N, O in main. Formally this means that the behaviour of your program is undefined.
Replace
cout << Q1() << endl;
with
cout << (E = Q1()) << endl;
and so on, and all will be well. See for yourself by using your line by line debugger.
Let's start from the beginning (which I think your might want to do to learn C/C++, perhaps by running through one of the many online C++ tutorials). I think your main focus should be on the following (in no specific order):
Initialization: Primitive data types like int, char, etc. are called Plain Old Datatypes (POD). In all the cases you are using in your code, they are not initialized, following the rule "don't pay for what you don't use." See What are POD types in C++? for more info.
Scope: Variables exist within a region of a program defined by where they are declared. For example, in main() you declare int E; (without initializing it so it simply acquires the value of whatever was in memory at that location). The scope of this E in main() starts where it is declared at ends at the end of main() (its scope is the function main).. Now we go to your function int Q1() in which you declare int E = 0;. At that point in the function this E comes into existence where it is declared and then goes out of existence at the end of Q1 (its scope is the function Q1). When you set E in Q1 that variable (and its value) disappears when you exit Q1, and so back in main when you add E, you are adding the E declared in main which just has a random value. Thus the E you used in main
extroversion+=E;
is not the same E you set in Q1
cin >> E;
They are different variables.
See https://www.tutorialspoint.com/cplusplus/cpp_variable_scope.htm for more info.
Functions: You are calling functions which return a value, but you don't use that returned value. I think that your misunderstanding of the scope of variables and the concept of a function is the root of your difficulties. Frex, in Q1() you return the value of E, which is indeed what you want. You just didn't know how to use it. In this instance, I would replace
cout << Q1() << endl;
extroversion+=E;
with
extroversion = Q1();
See http://www.cplusplus.com/doc/tutorial/functions/ for more info.
There are many issues with your code above that I think could be rectified by visiting some online tutorials like those I have referenced. I could rewrite your code but I think that (1) it should probably work with the suggestions I have given here and (2) you will learn more if you rewrite it yourself! :-) It also appears to me that you may have just kept adding things in order to get your code to compile that are not necessary. I might suggest that you go through each line and ensure that you understand why it is there (and why it is where it is).

Printing multiple outputs on same line

there. I'm self learning C++ out of "C++ without fear". There is an exercise dealing with the GCD of 2 numbers that asks to print "GCD(a,b) =>" at each step in the proceedure. I was able to get this working:
int gcd (int a, int b);
int main() {
int i,j;
cout << "Enter the first integer" << endl;
cin >> i;
cout << "Enter the second integer" << endl;
cin >> j;
int k = gcd(i,j);
cout << "The GCD is " << k << endl;
system("PAUSE");
return 0;
}
int gcd (int a, int b){
if(b==0){
cout << "GCF(" << a;
cout << "," << b;
cout << ") => " <<endl;
return a;
}
else {
cout << "GCF(" << a;
cout << "," << b;
cout << ") => " << endl;
return gcd(b,a%b);
}
}
I was just wondering if there is a nicer way to go about printing each step of finding the GCD. That is, is there a "nicer" way to write this part of the code:
cout << "GCF(" << a;
cout << "," << b;
cout << ") => " << endl;
? Thanks in advance.
You can do something like:
cout << "GCF(" << a << ',' << b << ") =>" << endl;
It is not C++ but you could use the C way of printing it which in my opinion looks better in this situation because there are far fewer stream operators, << in the way.
#include <cstdio>
printf("GCF(%d, %d) =>\n", a, b);
But this is a C way of doing things... You could use something like boost::format as is mentioned in this SO answer.
try this one
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
cout << 6+2 <<"\n" << 6-2;
}

c++ segmentation fault (core dumped) with modulus

I am working on a program that allows the user to practice division. My code is below:
//div1
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
using namespace std;
#define CLS "\033[2J\033[1;1H"
#define NEWLINE "\n"
int main() {
srand(time(NULL));
int a, div1, div2;
div1=rand()%11;
div2=rand()%11;
while (div2>div1) {
swap(div1,div2);
continue;
}
if (div1%div2!=0) {
return main();
} else {
cout << CLS;
cout << NEWLINE;
do {
cout << div1 << " / " << div2 << " = ?" << endl;
cin >> a;
cout << CLS;
cout << NEWLINE;
cout << "\t\tWrong!!" << endl;
cout << NEWLINE;
} while (a!=div1/div2);
cout << CLS;
cout << NEWLINE;
cout << "\t\tCorrect!!" << endl;
cout << NEWLINE;
cout << "Hit enter to continue." << endl;
cin.ignore();
cin.get();
return main();
}
return 0;
}
Basically, what it is supposed to do is first choose two random numbers. Then, it is supposed to check to see if the second number (div2) is greater than the first (div1), and if they are, it will switch them. Then, it will use the modulus (div1%div2) to make sure that the two numbers can be divided by each other without a remainder. If they cannot be divided without a remainder, it will restart the program (return main();). However, whenever I run it, I get the segmentation fault: core dumped, either when I start it or after running it a few times. Any ideas on how to fix this?
Thanks!!
Here's an example of what I've said in the comments. Obviously, you can refactor this so that it works more gracefully (as of now it'll give you floating point exceptions sometimes), but it gives you an idea on how to do this without calling main again.
NOTE: You do not need to make a constant for NEWLINE. There is already a built-in constant in std. In fact, you're already using that constant (endl). So you can just do cout << endl instead of cout << NEWLINE.
//div1
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
using namespace std;
#define CLS "\033[2J\033[1;1H"
#define NEWLINE "\n"
int main() {
while(true) {
srand(time(NULL));
int a, div1, div2;
div1=rand()%11;
div2=rand()%11;
while (div2>div1) {
swap(div1,div2);
continue;
}
if (div1%div2!=0) {
} else {
cout << CLS;
cout << NEWLINE;
do {
cout << div1 << " / " << div2 << " = ?" << endl;
cin >> a;
cout << CLS;
cout << NEWLINE;
cout << "\t\tWrong!!" << endl;
cout << NEWLINE;
} while (a!=div1/div2);
cout << CLS;
cout << NEWLINE;
cout << "\t\tCorrect!!" << endl;
cout << NEWLINE;
cout << "Hit enter to continue." << endl;
cin.ignore();
cin.get();
}
}
return 0;
}
This code can get into "divide by 0" error. This is why you would be getting error.
The line "if (div1%div2!=0) {" seems erroneous.
In this line if div2 == 0, then your code will crash.

How to start a newline in C++ while doing equations

Im reading through "The C++ Programming Language" and my current assignment is to make a program that takes two variables and determines the smallest, largest, sum, difference, product, and ratio of the values.
Problem is i can't start a newline. "\n" doesn't work because i have variables after the quote. And "<< endl <<" only works for the first line. I googled the hell out of this problem and im coming up short.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
inline void keep_window_open() {char ch;cin>>ch;}
int main()
{
int a;
int b;
cout<<"Enter value one\n";
cin>>a;
cout<<"Enter value two\n";
cin>>b;
(a>b); cout<< a << " Is greater than " << b;
(a<b); cout<< a << " Is less than " << b;
keep_window_open();
return 0;
}
You are looking for std::endl, but your code won't work as you expect.
(a>b); cout<< a << " Is greater than " << b;
(a<b); cout<< a << " Is less than " << b;
This is not a condition, you need to rewrite it in terms of
if(a>b) cout<< a << " Is greater than " << b << endl;
if(a<b) cout<< a << " Is less than " << b << endl;
You can also send the character \n to create a new line, I used endl as I thought that's what you were looking for. See this thread on what could be issues with endl.
The alternative is written as
if(a>b) cout<< a << " Is greater than " << b << "\n";
if(a<b) cout<< a << " Is less than " << b << "\n";
There are a few "special characters" like that, \n being new line, \r being carriage return, \t being tab, etc... useful stuff to know if you're starting.
You can output std::endl to the stream to move to the next line, like this:
cout<< a << " Is greater than " << b << endl;