C++ Code Results in Possible Console Output Error - c++

I am running this code from textbook: An Intro To Design Patterns in C++ with QT.
/* Computes and prints n! for a given n.
Uses several basic elements of C++. */
#include <iostream>
int main() {
using namespace std;
/*
*/
// Declarations of variables
int factArg = 0;
int fact(1);
do {
cout << "Factorial of: ";
cin >> factArg;
if (factArg < 0) {
cout << "No negative values, please!" << endl;
}
}
while (factArg < 0);
int i = 2;
while (i <= factArg) {
fact = fact * i;
i = i + 1;
}
cout << "The Factorial of " << factArg << " is: " << fact << endl;
return 0;
}
The output console only prints one line that says "Factorial is: "
Is that what it's suppose to do?

Yes that is what the program should output at first; it's waiting for you to type a number. If you would step into your code you would soon find out that it will wait for an input on the following line " cin >> factArg;".
So... Go ahead, type a number and press enter :).

Yes you code includes cin >> factArgwhich you will input in the terminal first before the program will run. You may want to put the using namespace std before the main function rather then in it.

Related

Can I do in c++ something more than just 'x++', or 'x--'?

I made here a program to do 3x+1 math problem. So I am asking, if I could write in a c++ code something like x/2;, or x*3+1. These stuff what i put here are with mistakes. Then, is it possible in c++ to do that? If yes, how?
Here's the code:
#include <iostream>
using namespace std;
int main() {
cout << "Write an integer.\n"; int x; cin >> x;
// I made here a program to do 3x+1 math problem.
while (x==1) {
if ((x%2)==0) {
x/2; cout << x << ", ";
} else if ((x%2)==1) {
x*3+1; cout << x << ", ";
}
}
return 0;
}
The output there was:
/tmp/GjudkYOaE4.o
Write an integer.
9
But I was waiting it to write the number 28, 14, and more, but it did nothing.
I can see that you are new to coding, I would suggest you to please read a good amount of information about if-elseif-else and while loop that you are using
I can show you a few corrections here
#include <iostream>
using namespace std;
int main() {
cout << "Write an integer.\n";
int x; cin >> x;
// I made here a program to do 3x+1 math problem.
while (x!=1) { // x!=1 could be one of the terminating condition so when your x becomes 1, the loop would end. But of course the terminating condition depends on what you are trying to achieve
if (x % 2 == 0) {
x = x/2; //you need to assign the value back to x
cout << x << ", ";
} else { // you dont need else-if here because there could only be 2 possibilities for %2 operaion here
x = x*3+1;
cout << x << ", ";
}
}
return 0;
}
Give value to the same variable with assignment operator ('='):
x = x*3+1;
or
x = x/2;

Finding prime numbers and then putting the prime numbers into an output file

So I have an assignment for class in which I have to ask the user for an integer in between 1 and 3000. Then my program should be able to tell if the integer is a prime number or not. Lastly, I would have to put that integer into a file, but only if it is a prime number. But my issue is my syntax, I am not sure if it's right(well actually obviously it's not because I keep getting errors). Is it possible to open a file in a function? and if so does it become a parameter?
I have been going through my textbook and googling as much as possible for some guidance but I'm still feeling lost. Any advice would help.
Edit: My logic as far as the numbers work, however when I add the code to write to a file, I'm now getting errors.
The two errors are
C2440 initializing: cannot convert from constant char to int (line 18)
C2079 myfile: uses undefined class'std::basic_fstream <>char,std::char_traits>'
Here's my code so far!
// Project 5.cpp : Defines the entry point for the console application.
//
#include <fstream>
#include "stdafx.h"
#include <iostream>
using namespace std;
//functions
void prime(int x);
//variables
int x=0;
int i;
char answer;
fstream myfile("castor_primes.txt");
int main()
{
do
{
cout << "Enter an integer between 1 and 3000 \n";
cin >> x;
if (x == 1)
{
cout << x << " is not a prime number.\n";
}
else if (x < 1 || x>3000)
{
cout << x << " is an invalid number. \n";
}
else
{
prime(x);
}
cout << "Do you want to enter another number? Y/N \n";
cin >> answer;
} while (answer == 'y' || answer == 'Y');
myfile.close();
return 0;
}
void prime(int x)
{
if (x == 2)
{
cout << "Yes, " << x << " is Prime\n";
}
else
{
for (i = 2; i < x; i++)
{
if (x%i == 0)
{
cout << x << " is not a prime number\n";
break;
}
}
if (x == i)
{
cout << "Yes, " << x << " is Prime\n";
myfile << x ;
}
}
}
#include "stdafx.h" includes a pre-compiled header file when using Microsoft Visual Studio. Check to see if that file exists and if it is correct (depending on the errors you see).
There is no reason to pass the outputFile into the prime() function since you are opening and closing it in the function. Although it works just fine if you do.
It is a parameter of the function call (if that is your question) and is a global variable since it is defined outside the main() function.
As some one else suggested the code functions if the aforementioned #include "stdafx.h" is removed, but I am not sure how that affects the compilation in Visual Studio.

Print out last line and then run program again Y/N

I am stuck on this random guessing game for school.
I have added the code that needed to be added, but the console keeps closing without returning the last strings.
I would also like to learn how to make the program run again with clicking Y to run again.
I am still learning C++, so any help would be appreciated.
Code:
// GuessingGameApp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>//added to run string
#include <locale>//added toupper run again
using namespace std;
int main()
{
//Seed the random number generator
srand(time(0));
int selectedNumber = rand() % 20 + 1; int numberOfTries = 0;
int inputtedGuess;
std::cout << "Guess My Number Game\n\n";
//Ask the user for a value until the correct number is entered
do {
std::cout << "Enter a guess between 1 and 20:";
std::cin >> inputtedGuess;
++numberOfTries;
if (inputtedGuess > 20 || inputtedGuess < 1) {
cout << "Your guess is out of range.\n\n";
}
else if (inputtedGuess > selectedNumber) {
cout << "Too high!\n\n";
}
else if (inputtedGuess < selectedNumber) {
cout << "Too low!\n\n";
}
}
while (inputtedGuess != selectedNumber);
//Congratulate the user and end the program
std::cout << "\nCongratulations! You solved it in " << numberOfTries << " tries!\n" << std::endl;
//fix problem with console closing and (add "play again" option), so I can
//learn
//printf; did not work... Break did not work..
//
return 0;
}
I was able to get the console to stay open by putting a break at line 33, but I want to learn how to do this correctly so I deleted the break.
The last line of your output should actually be printed. The reason why the last line "is not printed" is probably that your IDE closes the console before you can see the final output (though it should be there). Many IDEs allow to make the console visible after program termination. BTW: Note that when pasting the code you probably lost a << before std::endl in std::cout << "\nCongratulations! You solved it in " << numberOfTries << " tries!\n" std::endl; But this has actually to be a copy-paste problem, because your program would not have compiled otherwise.
Anyway, by providing a "Try again?"-logic, your program does not terminate and the problem is solved.
I'd suggest to provide a separate function performing the guess, which is then called in a do-while loop with the "Try again="-question.
void guess() {
// your code (except srand) goes here...
}
int main() {
srand(time(0)); //Seed the random number generator only once
char doAgain;
do {
guess();
cout << "Try again (Y/N)?";
cin >> doAgain;
}
while (toupper(doAgain)=='Y');
return 0;
}
As people suggested, you can add another do-while loop to repeat the game.
int choice = 0;
do {
// first part of code..
do {
// inner do-while
} while (inputtedGuess != selectedNumber);
std::cout << "\nCongratulations! You solved it in " << numberOfTries << " tries!\n" std::endl;
cout << "\nWould you like to play again?\n\n";
cout << "1 - Yes\n";
cout << "2 - No\n\n";
cout << "Choice: ";
cin >> choice;
} while(choice == 1);

Run Time Check failure #2:

Below is my code so far. I am just doing this step by step, for a class assignment. Trying not to give the whole code I just want to know what is wrong with what I have so I can learn to fix it. Thanks for the help.
The goal is to create class driver then to get total lap times, compare them and put them in order of 1st thru 3rd place. I've made this in a simple program already. Now I am trying to make an array of the class driver.
So far this is working, It asks for input correctly, and gives an output but before the end of the program I get:
Debug Error!
Run Time Check Failure #2 - Stack around the variable 'driver' was corrupted.
None of the answers I've found here make sense to my application. I have 0 failures when I run the build before running the program.
I also know not to use single character variables, I just do this as I learn what I'm missing and later change them.
#include <iostream>
#include <string>
using namespace std;
class Driver
{
int carNumber;
public:
void setNumber(int number)
{
carNumber = number;
}
int getNumber()
{
return carNumber;
}
};
int main()
{
int x;
int i;
Driver driver[3];
for (i = 1; i <= 3; i++)
{
cout << "Enter Driver " << i << "'s car number: ";
cin >> x;
driver[i].setNumber(x);
}
for (i = 1; i <= 3; i++)
cout << "driver " << i << "'s number is " << driver[i].getNumber() << endl;
return 0;
}
start for loop as shown below because as we know that array stores n elements from location 0 to n-1.
for (i = 0; i <3; i++)
{
cout << "Enter Driver " << i << "'s car number: ";
cin >> x;
driver[i].setNumber(x);
}
Your array access indexes are wrong.
Arrays start at index 0, not 1, and end at 1 less than the number of elements. So for a declaration of driver[3], the valid indexes are 0, 1, and 2, not 1, 2 and 3. With the wrong indexes, you're writing past the end of the array, causing the stack corruption.
Your write loop should be more like
for (i = 0; i < 3; i++)
{
cout << "Enter Driver " << i << "'s car number: ";
cin >> x;
driver[i].setNumber(x);
}
You'll need to make a similar fix to the read loop.

C++ cout won't work inside for and if?

I have those two pieces of code as my home assignment. The code looks all fine to me, but it won't print out what I want, no matter what. In fact, the console output remains completely empty.
The first program is supposed to print out all numbers that fulfil the ladna() function requirements and are between 1 and a:
#include <iostream>
using namespace std;
int a;
int i = 1;
bool ladna(int a)
{
if((((a>>4)*5+a*2)%3)==1)
return true;
else
return false;
}
int main()
{
cerr << "Podaj liczbe: " << endl;
cin >> a;
while (i <= a){
if (ladna(a)){
cout << i << " ";
}
i++;
}
}
the ladna() function is premade and I have to use it as is.
I tried changing while into do...while and for, didn't help. Doesn;t work with cerr either.
The second code has to print out all the natural divisors of number a.
#include <iostream>
using namespace std;
int main()
{
int a;
cerr << "Podaj liczbe" << endl;
cin >> a;
for (int i = 0; i >= a; i++){
if (a % i == 0){
cout << i << endl;
}
}
return 0;
}
Doesn't work either.
To me it looks like both pieces of code have the same issue, because they are written in the same way, based on the same principle, and the error is the same. Hence my assumption, that the cause is the same as well.
Unfortunately, for the love of me, I simply can't see what said error is...
For the first code:
I think you should call ladna function with i, like ladna(i)
For the second code:
In for it should be i<=a
'%' is the modulo operator, during the execution of (a%i) you divide a with i and take the remainder, since i start with zero you will get "Floating point exception (core dumped)" due to division by zero. So, for should start with 1. This should work:
for (int i = 1; i <= a; i++){
if (a%i == 0){
cout << i << endl;
}
}