Newbie struggles with std::cin - c++

I'm having an issue where a simple function appears to terminate when it reaches an std::cin request. The compiler throws no warnings or errors and no run-time errors occur, the program simply falls back to main menu.
Snippet:
#include <iostream>
#include <math.h>
using namespace std;
void circle()
{
float radius = 0.0f, diameter = 0.0f, circumference = 0.0f, area = 0.0f;
const float pi = 3.14f;
cout << "Enter radius." << endl;
cin >> radius;
cout << "Radius: " << radius << endl;
cout << "Diameter: " << 2*radius << endl;
cout << "Cirumference: " << 2*pi*radius << endl;
cout << "Area: " << pi * pow(radius, 2) << endl;
}
The function is called from main() and is successfully called as "Enter radius" appears on the screen, but no input is requested and the last 4 statements are skipped. The program then simply returns to main().
cin is also error free (and continues to work while playing in the main() function) so I don't think it's simply reading a bad character in the stream.
I just can't figure out why circle() quits unexpectedly.

It does the same on my machine when I try and run your code using Visual Studio 2010 on Windows XP.
I managed to fix it by putting getchar(); after the call to circle() in main.
Not sure why this is happening, hopefully someone can shed some more light on it.
**EDIT:
Of course it'll quit, it's because it'll run to the end of main which quits the app.

Well, it works fine on my computer. Did you debug it and does it really skips those lines? Add
cout << flush;
an the end to flush the buffer and see the results on the screen.
Remember to also clean the cin buffer before reading from it if you want it to block the executing program and wait for input from a user.

cin doesn't request input, but just reads from stdin. So you program will print out
Enter radius.
followed by a new line. Then you can just type the radius and hit return. Did you try that?

Related

I can't seem to get his c++ script to not return a 0 at one point

so when I run this code, the print_conclusion function (I'm assuming) seems to output an unwanted zero. Can someone please tell me how to not get this zero to show up by suggesting improvements to my code? Thanks
I'm just going to repeat my question so this isn't "mostly code"
so when I run this code, the print_conclusion function (I'm assuming) seems to output an unwanted zero. Can someone please tell me how to not get this zero to show up by suggesting improvements to my code? Thanks
I'm just going to repeat my question so this isn't "mostly code"
so when I run this code, the print_conclusion function (I'm assuming) seems to output an unwanted zero. Can someone please tell me how to not get this zero to show up by suggesting improvements to my code? Thanks
I'm just going to repeat my question so this isn't "mostly code"
so when I run this code, the print_conclusion function (I'm assuming) seems to output an unwanted zero. Can someone please tell me how to not get this zero to show up by suggesting improvements to my code? Thanks
[code]
//#include<stdio.h>
#include"stdafx.h"
#include<iostream>
#include<string>
//#include <cmath>
using namespace std;
double depth, temperatureCelsius, tempCelToFah;
char usersInput;
string print_introduction() {
// prints out information to tell the user what this program does.
//cout << "This program calculates the temperature of the earth when given a depth in kilometers" << endl;
return "This program calculates the temperature of the earth when given a depth in kilometers\n";
}
double celsius_at_depth(double depth) {
// computes and returns the celsius temperature at a depth measured in kilometers.
return temperatureCelsius = 10 * depth + 20;
}
double celsius_to_fahrenheit(double celsius) {
// converts a Celsius temperature celsius to Fahrenheit.
return tempCelToFah = 1.8*celsius + 32;
}
double print_conclusion(double depth) {
//return
// display the conclusion that what is the temperature in both Celsius and Fahrenheit at depth of the earth
//does all necessary calculations
celsius_at_depth(depth);
celsius_to_fahrenheit(temperatureCelsius);
cout << "The temperature at depth " << depth << " kilometers. In Celsius the temperature is " << temperatureCelsius << "\n... in Fahrenheit it is " << tempCelToFah << " degrees.\n";
return 0;
//I'm assuming the extra zero in my output comes from this return but I cannot figure out how to get rid of it!!!
}
int main()
{
//1. print introduction by calling print_introduction() function
cout << print_introduction() << endl;
//2. ask user to enter the depth
cout << "Please enter the depth in kilometers" << endl;
//3. get user’s input
cin >> depth;
//4. print out the conclusion by calling print_conclusion function
//cout << print_conclusion(depth); //did not work left zero
cout << print_conclusion(depth) << endl;
//5. ask user if he/she wants to continue
cout << "Would you like to continue? (y/n)?";
//6. get user’s input
cin >> usersInput;
//7. repeat step 2 to step 6 if user picks ‘Y’ or ‘y’
if (usersInput == 'Y' || usersInput == 'y')
{
main();
}
else {
//Stop program
return 0;
}
}
[/code]
Cout will print the output of the function.
Hence, you shouldn't print the output of your function to avoid the 'extra zero'
print_conclusion(depth);

C++ program crashes when using cout to output a double?

I'm trying to write a simple c++ program that takes a number of miles as input and returns a conversion to kilometers. Here is my kilo.cpp:
#include <iostream>
using namespace std;
int main()
{
double miles;
double km_to_mile = 1.609;
cout << "Please enter number of miles: ";
cin >> miles;
miles *= km_to_mile;
cout << "That is " << miles << " kilometers.";
}
The program compiles, but when I run it it crashes when it tries to output the double. The last line I get in console is "That is " and I get the Windows error message "kilo.exe has stopped working."
I've tried a few other code samples and whenever I try to use cout to output a double value, the program crashes with the same error. I assume this is some problem with my compiler (mingw on Windows 8.1), but I've tried reinstalling the compiler a few times now to no avail.

Alternative to system("Pause"); revisited

I know this question has been asked a million times, but I have a coding question with it, because a couple of alternatives seem not to work with this code, and I'm not sure why. If you look right before the return 0;, I'm trying cin.get() and it doesn't stop the program, and neither does my PressEnterToContinue() function that I found somewhere that worked on other programs. The only thing I've gotten to work with this is system pause, which I don't want to use, since I will also be using this cross platform. Any ideas?
#include <iostream>
using namespace std;
void PressEnterToContinue()
{
std::cout << "Press ENTER to continue... " << std::flush;
std::cin.ignore(std::numeric_limits <std::streamsize> ::max(), '\n');
}
int main(void)
{
int pause;
double distance, x1, y1, x2, y2, x, y;
cout << "This program outputs the distance between two points on a plane!" << endl;
cout << "Please input point X1" << endl;
cin >> x1;
cout << "Please input point Y1" << endl;
cin >> y1;
cout << "Please input point X2" << endl;
cin >> x2;
cout << "Please input point Y2" << endl;
cin >> y2;
x = x2 - x1;
y = y2 - y1;
distance = sqrt(x*x + y*y);
cout << distance << endl;
//cin.get();
//PressEnterToContinue();
//system("Pause");
return 0;
}
Feel free to mention methods of stopping the system that I don't have here. Thanks,
It's because your last input (cin >> y2) leaves the newline in the input buffer. This is then read by your calls to cin.get() or PressEnterToContinue().
In the PressEnterToContinue function you might want to "peek" at the input buffer to see if there is any characters first, and if there is then do an extra cin.ignore.
When you do e.g.
cin >> y2;
And you enter the input
123\n
Then the input buffer will contain the string "123\n". After the input operator extracts the number (123) the input buffer will contain "\n", which is that the cin.get() call reads.
To solve this problem, you simply have to flush the buffer. The number 10000 in the example is just the number of characters to clear from the buffer.
cin.ignore(10000);
cin.get();
And to answer why cin >> y2 leaves a newline character in the buffer is because you entered a newline character by hitting the return key, and by retrieving the data from the console into your variable you leave the newline character behind.
Technical problem: characters (sometimes just a newline) left in the input buffer.
That said, there is never any need for the program stopping itself at the end, so a system( "pause" ) or whatever stopping action has no advantage, and some problems, including portability.
Run your program from the command line.
Or, since you're programming in Windows, use Visual Studio and run the program via Ctrl F5.
Or, place a breakpoint on the last right brace of main and run the program via a debugger, e.g. in visual studio by hitting F5.

Win32 Console Application won't run in VS2012 Pro

I am teaching myself C++ with Prata's C++ Primer Plus and am having an issue. I don't get any errors in VS2012 Pro and the program compiles successfully but gives me an unhandled exception (Unhandled exception at 0x76ED016E (ntdll.dll) in Prata 2.5.exe: 0x00000000: The operation completed successfully.) when I try to enter C or F as my initial option and I am not sure where I have gone wrong. The exercise only asked me to create a simple program that converted Fahrenheit to Celsius, but I thought that I would find something like this useful as I often use online sources to do this conversion. If I had my own program, I wouldn't have to worry and can expand it to a non CLI version and more conversion options (ie. yards to metres etc). Any help would be appreciated.
#include "stdafx.h"
#include <iostream>
// Function Prototypes
double convertToF(double);
double convertToC(double);
int main()
{
using namespace std;
char* convertChoice = "a"; // Initializing because the compiler complained. Used to choose between celsius and fahrenheit.
int choiceNumber; // Had issues using the char with switch so created this.
double tempNumber; // The actual temperature the user wishes to convert.
cout << "Do you wish to convert to [C]elcius or [F]ahrenheit?";
cin >> convertChoice;
// IF() compares convertChoice to see if the user selected C for Celsius or F for fahrenheit. Some error catching by using the ELSE. No converting char to lower though in case user enters letter in CAPS.
if (convertChoice == "c")
{
cout << "You chose Celsius. Please enter a temperature in Fahreinheit: " << endl;
cin >> tempNumber;
choiceNumber = 1;
}
else if (convertChoice == "f")
{
cout << "You chose Fahrenheit Please enter a temperature in Celsius: " << endl;
cin >> tempNumber;
choiceNumber = 2;
}
else
{
cout << "You did not choose a valid option." << endl;
}
// SWITCH() grabs the int (choiceNumber) from the IF(), goes through the function and outputs the result. Ugly way of doing it, but trying to make it work before I make it pretty.
switch (choiceNumber)
{
case 1:
double convertedFTemp;
convertedFTemp = convertToC(tempNumber);
cout << convertedFTemp << endl;
break;
case 2:
double convertedCTemp;
convertedCTemp = convertToF(tempNumber);
cout << convertedCTemp << endl;
break;
default:
cout << "You did not choose a valid option." << endl;
break;
}
// To make sure the window doesn't close before viewing the converted temp.
cin.get();
return 0;
}
// Function Definitions
double convertToF(double x)
{
double y;
y = 1.8 * x + 32.0;
return y;
}
double convertToC(double x)
{
double y;
y = x - 32 / 1.8;
return y;
}
I also don't know if I have everything right. ie. The formula in the functions as well as the order of the switch. Please don't correct that, I'll figure that out for myself once the damn thing compiles. :)
Please refer to the rule of thumb in the comments. You are using a char* without enough knowledge of the details to use it properly. Use std::string, it will do exactly what you need.
For future reference: With a char*
you need to allocate memory
you need to use strcmp to compare
you need to watch the length yourself
you need to deallocate the memory
That's a lot for starters. Use std::string.
string convertChoice = "a";
Don't forget to
#include <string>

C++ cin positive integers only

This is my first time on Stackoverflow.
I was making a program to find out MPG for a car. I was wondering how can I make the cin statement only accept positive integers only? and also, if you do enter a invalid input, can you reset it? I am not sure if that makes sense. I didn't have to do this for class. I was just curious on how to do it. Here is the code.
#include <iostream>
using namespace std;
int main()
{
double tank, miles, mpg;
cout << "Hello. This is a program that calculates the MPG ( Miles Per Gallon) for your\n" ;
cout << "vehicle\n" << endl;
cout << "Please enter how many gallons your vehicle can hold\n" << endl;
cin >> tank;
cout << endl;
cout << "Please enter how many miles that have been driven on a full tank\n" <<endl;
cin >> miles;
cout << endl;
mpg = (miles)/(tank);
cout << "Your vehicle recieves " << mpg << " miles per gallon\n" << endl;
system ("pause");
return 0;
}
iostreams are not a toolkit for building a complex UI. Unless you want to write your own rather complex stream to wrap the usual stream, there is no way you are going to get it to either (a) only accept positive integers or (b) interact politely with a user who types in something else.
You should just read lines from cin, and print your own error prompts and such after you look at what you get.
cout << "Hello. This is a program that calculates the MPG ( Miles Per Gallon) for your\n" ;
cout << "vehicle\n" << endl;
do
{
cout << "Please enter how many gallons your vehicle can hold\n" << endl;
cin >> tank;
cout << endl;
} while (tank <= 0 && ((int)tank != tank));
do
{
cout << "Please enter how many miles that have been driven on a full tank\n" <<endl;
cin >> miles;
cout << endl;
} while (miles <= 0 && ((int)miles != miles));
If you do this after running the statements it will rerun them if the answer is 0 or lower or is not an integer. If you make the variables ints instead of doubles then you can remove the "&& ((int)miles == miles)" part of the while statement.
Still, there are a couple of standard ways to do it in a command line environment.
You could trap the cin statement in a loop that doesn't release until a valid input has been entered. This is the "standard" way to validate CLI input, not just signed numbers.
do
{
cout << "\nPlease enter...";
cin >> tank;
}
while (tank < 0)
The condition in the while statement is the place to validate the data. You can also make an if statement to explain why the input is invalid.
The other way is to simply force the value to be positive, by simply going tank = fabs(tank);, which takes the absolute value (i.e. positive) of the tank variable.
So this is my code for an infinite loop
1: So main will call the "Get_number()" function
2: Get number will accept an int from the user
3(A): If int is greater than 0, go into loop
3(B): Else, display to user "Invalid Input" and then call the function
"Get_number()" again creating an infinite loop until the user
enters a value greater than 0
#include <iostream> // Access the input output stream library
#include <fstream> // Access to the fstream library (used to read and write to files)
#include <chrono> // Needed to access "std::chrono_literals"
#include <thread> // Needed to access "namespace std::this_thread"
using std::fstream; // this will allow us to use the fstream (we'll be able to read and write to files)
using std::ios; // needed for iostream (used to be able to tell fstream to read and/or write to a file and that it's reading/writing a binary file)
using std::cout; // need this statment to access cout (to display info to user)
using std::cin; // need this statment to access cin (to gather info from user)
using std::endl; // need this statment to access endl (will end the line)
using namespace std::this_thread; // This will allow me to use "Sleep_For" or "Sleep_Until"
using namespace std::chrono_literals; // This will allow the use of measurements of time such as ns, us, s, h, etc.
//Prototypes***************************************************************************************************
void shellSort(int read[], int readLength); //Making Prototype (Declaring our function) so that compiler knows not to worry about it
void Get_number();
void Write_to_file(int user_input_of_how_many_random_numbers_to_generate); //Making Prototype (Declaring our function) so that compiler knows not to worry about it
void Read_from_file(int user_input_of_how_many_random_numbers_to_generate);//Making Prototype (Declaring our function) so that compiler knows not to worry about it
//*************************************************************************************************************
void main()
{
Get_number();
system("pause>>void"); // will let the console pause untill user presses any button to continue
}
/**************************************************************************************************************
* Purpose: This function will gather a positive integer from the user and use it to generate that many
* random numbers!
*
* Precondition: None
*
*
* Postcondition:
* Would've gathered the number of random numbers the user wanted to generate and then gone into the
* Write_to_file and Read_from_file function
*
**************************************************************************************************************/
void Get_number()
{
int user_input_of_how_many_random_numbers_to_generate = 0; //make variable that will accept the int value the user wants to generate random numbers
cout << "Please Enter A Number Greater Than Zero:" << endl; // displays to user to enter a number greater than zero
cin >> user_input_of_how_many_random_numbers_to_generate; // will accept the value the user inputted and place it in the "user_input_of_how_many_random_numbers_to_generate" variable
system("cls"); // Will clear the screen
if (user_input_of_how_many_random_numbers_to_generate > 0) // if user input is greater than zero, enter this
{
Write_to_file(user_input_of_how_many_random_numbers_to_generate); // will bring up the "Write_to_file" function
Read_from_file(user_input_of_how_many_random_numbers_to_generate); // will bring up the "Read_from_file" function
}
else // else enter this
{
cout << "invalid input!" << endl; // display to user "invalid input"
sleep_for(2s); // system will pause for 2 seconds allowing the user to read the message of "invalid input"
system("cls"); // console will be cleared
Get_number(); // Get_number function will be entered creating an infinate loop untill the user's input is valid!
}
}
Instead of
cin >> miles;
Try
while ( (cin >> miles) < 0 )
cout << "Please enter how many gallons your vehicle can hold\n" << endl;
That will repeat the question until the input is positive. You can do that for the rest of the questions too.
Note that input streams are not intended for input filtering. You have to provide your own logic for that.