lundi 22 mai 2017

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://ift.tt/2rqGrH4 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 :(

Aucun commentaire:

Enregistrer un commentaire