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

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.

Related

vs code terminal window show file location. In C-C++

I used to make basic program of C/C++ in vs code. After 2-3 weeks. in it's terminal it is not showing variable in output window. after making program when i run code.when i hit enter key it shows in terminal--it is not an error but code is not working.
PC C:\User\Owner\Desktop\C-C++>
WHEN I HIT ENTER IT AGAIN SHOW
PS C:\User\Owner\Desktop\C-C++>
IT DOES NOT SHOW 'ENTER VALUE OF B=='
IN THE TERMINAL OUTPUT WINDOW:-
for ex-:
#include <iostream>
using namespace std;
int main()
{
int a, b, c;
cout << "ENTER VALUE OF A==";
cin >> a;
cout << "ENTER VALUE OF B==";
cin >> b;
c = a + b;
cout << "ADDITION OF VALUES" << c;
return 0;
}
IN THE TERMINAL WINDOW IT SHOWS.
ENTER VALUE OF A==5 ( WHEN I PRESS ENTER )
THEN IT SHOWS
PS C:\User\Owner\Desktop\C-C++>5
5
AGAIN
PS C:\User\Owner\Desktop\C-C++>
PLEASE ANSWER THIS PROBLEM :(

Code doesn't work as intended in visual c++ (examples from bjarne stroustrup programming and principles book 2n version)

Okey as I've recently started to read about C++ and try to go with the book I'm having Programming Principles and practice Using C++ 2nd version.
I'm a total newbie so this is probably why, but here goes.
Okey so in the book they have you implement a header .h file instead of the (iostream) etc. So it just have all those for the start as the book doesn't want us to focus on those libraries in the start of the learning.
So i implemented it and used it (not sure if this is related to the problem). Anyway at page 77, I'm getting stuck.
Basically it's a wrong value that's getting entered and it's supposed to just show -1(or 0) as the int gets a false value, etc Carlos(letters, not an integer) so the int doesn't get a correct value so the code that is supposed to work (and show 0 or -1 as it's an incorrect value that's entered) is this according to the book:
#include "std_lib_facilities.h"
using namespace std;
int main()
{
cout << "Please enter your first name and age\n";
string first_name = "???"; // string variable // ("???” means “don’t know the name”)
int age = –1; // integer variable (–1 means “don’t know the age”)
cin >> first_name >> age; // read a string followed by an integer
cout << "Hello, " << first_name << " (age " << age << ")\n";
}
and this is what i wrote:
#include "std_lib_facilities.h"
using namespace std;
int main()
{
cout << "Please enter your first name and age" << endl;
string First_Name = "???";
int Age = -1;
cin >> First_Name >> Age;
cout << "Hello, " << First_Name << "(age" << Age << ")" << endl;
keep_window_open();
return 0;
}
However, the result with visual c++ for me is a crash when i for example write 22 Carlos.
According to the book it's supposed to output Hello, 22 (age -1)
But for me it just crashes after i enter the word Carlos as value for age...
I don't get a a error or anything when i run and compile it, but it crashes after when i give the false value for age.
What am i doing wrong?
add: I know i can use a string to get it to work, however I'm just interested in why it doesn't work as I'm following this book i wish to follow it without having these kind of problems as it's intended to work.
Here is a gif when im doing it:
http://imgur.com/a/ERjhz
Solution: To use system("pause"); instead of keep_window_open();
however it's still annoying to read the book with the knowledge that the code in the book doesn't work always :(
Well it is isn't a problem but too fast to be noticed by our eyes.
i am adding the function definition of keep_window_open()
inline void keep_window_open()
{
cin.clear();
cout << "Please enter a character to exit\n";
char ch;
cin >> ch;
return;
}
As you can see it simply takes the character input from the us
Forward you will learn about input stream and its buffer
So when you input a character in place of integer there is error flagged in the stream(background) and the only one of the characters input is used(in your case 'C' is used for flagging).
I am using input as Carlos 22
So now the input stream is still having characters 'a','r','l','o','s',22
so now the 'a' is used as a input for keep_window_open function
and the program ends without waiting for a input from you
So there is no error or crash but since the character is already there for input for keep_window_open function so its kind of really fast
The problem is in keep_window_open. It's a tricky function that is very hard to get absolutely right. You can replace it with this code that sidesteps the problem but only works on Windows:
inline void keep_window_open()
{
system("pause");
}
or with this slightly more complicated code that tries to take more cases into account:
inline void keep_window_open()
{
cout << "Please enter a character to exit\n";
if (!cin)
{
cin.clear();
cin.ignore(120, '\n');
}
char ch;
cin >> skipws >> ch;
}
(This assumes you don't enter lines longer than 120 characters. Replace 120 with numeric_limits<streamsize>::max() if you want it to be free from arbitrary limits. Other functions from std_lib_facilities.h do use 120 in this situation. You many or may not have to add #include <limits> directive to your program).
I have tested in a couple of cases and it appears to work with both correct and incorrect input to the program, but use it at your own risk. It still may or may not work correctly if your program requires more complicated input.
A good rule is to always except that the end users is idiots, so you need to write the program in a way that can handles all kinds of inputs without crashing. Therefore always read input numbers as std::string and then try convert it to int, short, double, unsigned int or what ever datatype you are using.
Your code should look like:
#include <cstdlib>
#include <exception>
#include <iostream>
#include <stdexcept>
#include <string>
int main(int argc, char **argv)
{
int age;
std::string first_name;
std::string input_age;
std::cout << "Please enter your first name and age: " << std::endl;
std::cin >> first_name >> input_age; // Read the age as 'std::string'
try
{
age = std::stoi(input_age); // Try to convert age from 'std::string' to 'int'
std::cout << "Hello, " << first_name << " (" << age << ")" << std::endl;
}
catch(std::invalid_argument& ex) // 'std::stoi()' will throw 'std::invalid_argument' if it's not able to convert 'std::string' to 'int'
{
std::cerr << "Unable to convert input value ('" << input_age << "') to 'int'" << std::endl;
std::cerr << "Debug info: " << ex.what() << std::endl;
}
catch(std::out_of_range& ex) // 'std::stoi()' will throw 'std::out_of_range' if 'std::string' is too small or too big to store in a 'int'
{
std::cerr << "The input value (" << input_age << ") is out of range, please input a value inside the range" << std::endl;
std::cerr << "Debug info: " << ex.what() << std::endl;
}
return EXIT_SUCCESS;
}
So it's nothing to do with code, it's something to do with input.
when i for example write 22 Carlos.
The problem is that the code is asking for First_Name then Age, Not Age then First_Name. So when you put 22 for First_Name, the .exe got confused.
for example lets say I did this
int y = 0;
cout << "Give me INT: ";
cin >> y;
cout >> "You put: " >> y;
And when I run the program and put this for input
Give me INT: ghaisewofasd
*crashed*
This is a problem because the user is giving a string for when the code is asking for a int.
So for your case, instead of writing 22 Carlos, just write Carlos 22.
Also keep in mind, this book maybe not so correct, because it shouldn't print out Hello, (22). Now a days stuff like that crash if that happens, maybe it was a older version of C++.

undefined reference to WinMain, [Error] Id returned 1 exit status

What have I screwed up here? There can be no hard coded values in the code which is why all my prompts are constants. We also have to call a user defined function to verify input.
Im getting the following error when I compile -- undefined reference to WinMain, [Error] Id returned 1 exit status I'm using Dev C++ as an IDE
#include <iostream> //for I/O
#include <iomanip> //for formatting output
using namespace std;
const string PROGRAM_DESCRIPTION = "Program will calculate the amount "
"accumulated every month you save, \nuntil you reach your goal. ";
const string ENTER_DOLLAR_AMOUNT_MONTHLY = "Enter the dollar amount to be "
"saved each month: ";
int main()
{
double dollarSavedPerMonth;
//displays program description
cout << PROGRAM_DESCRIPTION << endl << endl;
//Prompts user to enter dollar amount to be saved monthly, will validate
//input by calling VerifyDollar
dollarSavedPerMonth = VerifyDollar(ENTER_DOLLAR_AMOUNT_MONTHLY);
cout << endl;
return 0;
}
double VerifyDollar (string Prompt)
{
const string INVALID_DOLLAR_AMOUNT = "Invalid amount, re-enter monthly "
"savings amount.";
double dollarSaved;
cout << Prompt;
cin >> dollarSaved;
while (dollarSaved < 5 || dollarSaved > 5000)
{
cout << INVALID_DOLLAR_AMOUNT;
cout << endl;
cout << Prompt;
cin >> dollarSaved;
}
return dollarSaved;
}
You do indeed lack a WinMain() function anywhere in that code.
If memory serves me well, WinMain() is the entry point for a Win32 GUI app. I am assuming your IDE asked you for a "project type" of some sort, and you asked for a Windows app instead of a Console one.
Under that assumption, something in your project is configured to call WinMain(), which you did not define, hence the linker error.

programme not running correctly on dev c++

I'm new to c++ I'm trying to do a simple programme that calculates the weekly pay. See source code below. When I run the programme it lets me enter the workHours but when I click enter the programme closes n does not proceed to the rest of the code. Not sure where I'm going wrong please help.
#include <iostream>
using namespace std;
int main ()
{
int workDays;
float workHours, payRate, weeklyPay;
workDays = 5;
payRate = 38.55;
cout<< "Enter the number of hours worked: ";
cin >> workHours;
cin.ignore ();
weeklyPay = workDays * workHours * payRate;
cout << "Weekly Pay = ";
cout << weeklyPay;
cout << '\n';
return 0;
}
The DevC++ doesn't pause the program after it ends you have to add this feature by yourself:
First include conio.h
#include <conio.h>
Then at the bottom of the main add getch()
getch();
What compiler you are using as i am to run this code?
I am using visual studio 10 as IDE and it is working for me.

Newbie struggles with std::cin

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?