how to rewrite this c++ simple code? - c++

the code bellow is a c++ code that works just perfectly, the teacher asked us to rewrite it in order to have the input and output in only one instruction.
i really don´t know how to, and i have done research for hours.
i'll really appreciate a hint on how to do this.
#include <iostream>
using namespace std;
int main()
{
int c;
cin >> c;
std;
if(c == 0) {
cout << "user sent 0" << endl;
}
else {
cout << "user sent a number different from 0" << endl;
}
return 0;
}
thanks for reading.

If your teacher considers an if-else statement as one instruction, I can propose this one:
#include <iostream >
using namespace std;
int main() {
int c;
if ( (cin >> c) && c==0 )
cout << ”user sent 0” << endl ;
else cout << ”user sent a number different from 0” << endl ;
return 0;
}
If he sees it more strictly, then you can try :
int c;
cout << ( (cin >> c) && c==0 ? "user sent 0" : "user sent a number different from 0" ) << endl;
return 0;
Conceptually, I love the last one. But when I read it again, it reminds me B.Kernighan's famous quote : "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

This is the smallest I can do:
std::cout << (std::cin.get() == '0' ? "user sent 0" : "user sent a number different from 0");

Related

cin not accepting user input in C++

I'm a beginner in programming, and I'm trying to make a program that calculated how much radiation you've been exposed to throughout your life. For some reason, the 'cin' in my xray function doesn't accept user input, and just exits with code 0.
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <stdlib.h>
#include <string>
#include <sstream>
using namespace std;
bool nearpowerplant;
int XRay; // the amount of times you got an x-ray
double tRads = 0; // your total dose of radiation in your lifetime, measured in mSv (millisievert)
int age;
//the sleep function
void sleep() {
Sleep(1000); // 1000 miliseconds = 1 second
}
/*
>system("CLS")< for clear the console
*/
//introduction and pretty much the menu
void intro() {
cout << "Welcome to the Radiation Level Calculator" << endl;
sleep();
cout << "Conceptualized and created by Anatoly Zavyalov" << endl;
sleep();
cout << "Press the ENTER key to begin." << endl;
cin.get();
}
//introduction to general questions
void genintro() {
// intro to the medical
system("CLS");
sleep();
cout << "Let's begin with general questions." << endl;
sleep();
cout << "Press the ENTER key to continue." << endl;
cin.get();
}
//medical questions
void Age() {
//age
system("CLS");
cout << "How old are you?\n" << endl;
sleep();
cin >> age;
if (age <= 0) {
cout << "Your age can't be less or equal to 0." << endl;
Age();
}
else {
tRads += (age * 2);
sleep();
cout << tRads << endl;
}
}
//live close to powerplant?
void powerplant() {
system("CLS");
cout << "Do you live within 75 kilometers of a nuclear powerplant?" << endl;
sleep();
cout << "If yes, type YES. If no, type NO." << endl;
cin >> nearpowerplant;
if (nearpowerplant = "YES") {
tRads += (age * 0.01);
}
else {}
sleep();
cout << tRads << endl;
}
void xray() {
system("CLS");
cout << "How many times have you had an x-ray?\n" << endl;
sleep();
cin >> XRay;
if (XRay < 0) {
cout << "You can't have an x-ray a negative amount of times." << endl;
}
else {
tRads += (XRay * 3.1);
}
sleep();
cout << tRads << endl;
}
//main function, put all of the loops into here
int main() {
intro(); // the introduction
genintro(); // medical intro
Age(); // asks for age
powerplant(); // asks if lives close to powerplant
xray(); // asks for x-ray
return 0;
}
EDIT: I have edited the post to include the whole code. By the way, I am using Visual Studio Community 2017.
bool nearpowerplant;
nearpowerplant is a bool. It is true or false. That is it. It's worth noting that there is no reason for this variable to be globally accessible and consuming storage for the entire run of the program. It is used twice in the program, both times in the same function. It should be an Automatic variable scoped by the function that uses it.
cout << "If yes, type YES. If no, type NO." << endl;
cin >> nearpowerplant;
Reading "YES" or "NO" into a variable of type bool fails. cin cannot convert the string input into a boolean value and cin stops accepting input until the error is cleared. It's also a good idea to remove the garbage input that caused cin to fail or guess what? cin's just going to fail again. There are hundreds of SO questions on how to handle this, so I'm just going to drop keywords here: clear and ignore.
Takeaways: Make sure the data entry matches the type of the data being entered into and test the stream after every read to make sure the read succeeded.
eg:
if (cin >> nearpowerplant)
{
// do stuff
}
else
{
// clean up
}
This solves OP's visible error, but since it is heavily entwined with the next bug they are likely to find, we might as well cover it as well.
if (nearpowerplant = "YES") {
tRads += (age * 0.01);
}
else {}
if (nearpowerplant = "YES") { uses = (assignment) where it should use == (comparison). C++ is unforgiving here because this will compile. What it really did was takes the address of the string literal "YES", test that it's not null, and set nearpowerplant to the result. Since the address of the string literal is never going to be NULL, the result is always true, and when the if tests the result, the if will always enter.
Eg: http://ideone.com/4QL2jn
So what we need is something more like
cout << "If yes, type YES. If no, type NO." << endl;
string temp;
cin >> temp;
if (temp == "YES") {
tRads += (age * 0.01);
}
else {}
Note this will skip if the user inputs "yes", "y", "Yes" or anything other than exactly "YES". How you deal with this is up to you, but std::tolower and std::transform may help somewhat.
I think with sleep() comes undefined behavior, you should test it without, the os handles user-input and you do not have to care about the user typing in. endl flushes cout, so the text is directly shown.
Edit:
Maybe system("CLS") or sleep produces a silent error.

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);

Why does this cause in infinite loop with chars but not doubles?

I feel like im doing something really silly wrong. I just want the program to tell the user when they are entering non-doubles, and continue to loop back to the cin where you enter a value.
I want the user to input any number. Then essential do this trivial math and repeat. Its working fine in that regard, the problem comes when some unexpected input like a char gets entered. Then the input somehow sends it into a loop where it loops the math problem, instead of just telling the user that they must type a number and looping back to cin type in a new number.
#include <iostream>
#include <cstdlib>
using std::cout; using std::cin; using std::endl;
long double domath(long double i)
{
cout << i << "/" << 2 << "=" << i/2 << endl;
cout << i/2 << "*" << 10 << "=" << (i/2)*10 << endl << endl;
cout << 5 << "*" << i << "=" << 5*i << "\n\n";
return 0;
}
int main()
{
long double in = 0;
while(true)
{
cin >> in;
if (cin.fail()) {
in = char(int(in));
}
domath(in);
}
system("pause>nul");
return 0;
}
You don't clear the cin in case of fail, and it infinitely tries to parse wrong input to double, failing every time. You need to clear the buffer in case of error:
if (cin.fail()) {
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
in = char(int(in));
}
Also, can't understand what you're trying to achieve with
in = char(int(in));
in is a long double variable and will hold the last value you assigned to it, no need to "convert" it to do math.
Couldn't you try doing something like this?
int x;
if(std::cin >> x)
doSomethingCool(x);
else
std::cout << "Error, not a valid integer!" << std::endl;
Exit your loop on bad input.
I think this just feels more natural/looks cleaner than clearing the buffer and all the other jazz. Just my opinion.
if (cin >> x) - Why can you use that condition?
edit: Bul's answer is still a good one though.

Verify if string contains at least one letter

Hello Im trying to check if string contains at least one letter, but at this stage is not working. If I type 13 it would continue without giving me error,
It doesn't matter if contains number I just want at least one letter for example: Patrick1 thats okay.
This the code I'm trying :
void setName(string b) {
cout << "Please enter your name:" << endl;
getline(cin, b);
for (int i =0; i<b.size(); i++) {
if ((b[i] >= 'A' && b[i] <= 'Z') ||
(b[i] >= 'a' && b[i] <= 'z')) {
cout << "Error" << endl;
cout << "Please enter your name:" << endl;
getline(cin, b);
}
any suggestions thanks guys !
The C++ standard library have many nice algorithmic functions, for example one called std::any_of which will return true if any element in the range passed to causes a predicate to return true.
Can be used with ::isalpha like this
if (std::any_of(std::begin(b), std::end(b), ::isalpha))
{
// There is at least one alphabetic character in the string
}
Important note: The std::any_of function was introduced in C++11. Some compilers need special flags to enable C++11. Very old compilers and standard libraries might not have the function at all.
please try to avoid repeating yourself (like you did with "getline")
If you have to, rethink your algorithm ... in your case it could be something like " repeat the entry while there's no correct name entered", which can be coded exactly that way:
this way, if you want to change the code in place A, you cannot forget to also change it in place B (and all the other places you eventually copied it to) ;-)
#include <algorithm>
#include <iostream>
#include <cctype>
void setName(std::string& b) {
bool isValidName=false; // nothing entered yet
while ( !isValidName )
{
std::cout << "Please enter your name:" << std::endl;
std::getline(std::cin, b);
if (std::any_of(std::begin(b), std::end(b), ::isalpha)) {
isValidName=true; // correct name entered
}
else {
std::cout << "Error" << std::endl;
}
}
}
int main() {
std::string name;
setName(name);
std::cout << "Hello, " << name << "!" << std::endl;
return 0;
}