C++ και έλεγχος δεδομένων.

WiludrakeGR | Κυρ, 01/13/2008 - 23:27 | 3' | 2

Εχω φτιαξει ενα πολυ απλο προγραμματάκι στο οποιο βάζεις το ονομά σου
και το έτος γέννησης, και αυτο με την σειρά του, σου εμφανίζει ποσο
χρονών είσαι (κάνοντας 2007-birthYear).

Εχω μια μεταβλητη int birthYear στην οποια εκχωρείται η τιμή της από
τον χρήση μέσω της εντολής cin. Ετρεξα το πρόγραμμα και ολα δουλεύουν
ρολόι.

Δοκιμασα όμως, αντι να δώσω μια αριθμιτική τιμή στην
birthYear, να δώσω ένα χαρακτήρα. πχ a. μετα δοκιμασα aaa. Μετα edf. Το
αποτέλεσμα ήταν ότι τελικά είμαι -134514989 χρονών.

Ετσι έφτιαξα το εξής:
<pre>
#include <string>
#include <iostream>

int main() {
using namespace std;
const int THISYEAR = 2007;
string yourName;
int birthYear;

cout << 'What's your name ? ' << flush;
getline(cin, yourName);

cout << 'What year were you born? ';
cin >> birthYear;

if (THISYEAR-birthYear==-134514989) {
cerr << 'This is not valid.'
<< ' Try again...' << endl;
} else {

cout << 'Your name is ' << yourName
<< ' and you are approximately '
<< (THISYEAR-birthYear)
<< ' years old. ' << endl;
}
return 0;
}
</pre>
Τώρα αν δωσω χαρακτήρα αντί για αριθμό, το πρόγραμμα βγαζει το σχετικο
μύνημα και τερματίζει. Τι μπορώ να κανω για να μην τερματίζει αλλά να
με ξαναρωτάει για δώσω τιμή στην birthYear ;

ΥΣ:Δοκιμασα με do...while() αλλα για καποιο λογο κατι κανω λαθος και γεμίζει το buffer output.
WiludrakeGR2007-11-24 16:52:44

Δώσε αστέρια!

MO: (ψήφοι: 0)

Σχόλια

Hello man,
τσέκαρα τον κώδικα σου και άλλαξα το if από

if (THISYEAR-birthYear==-134514989) {

cerr << 'This is not valid.' << ' Try again...' << endl;

}

else {

cout << 'Your name is ' << yourName << ' and you are approximately '

<< (THISYEAR-birthYear) << ' years old. ' << endl;

}
σε
if ( (THISYEAR-birthYear)<0)
{
cerr << 'You can not have negative age.'<< ' Try again...'

<< endl;
}
if ( (THISYEAR-birthYear)==0)
{
cerr<< 'It is imposible. You must be the youngest internet user of the world!!!'<<< 'Your name is '

<< yourName<< ' and you are approximately '<<(THISYEAR-birthYear)<< ' years old. '<< endl;
}

Είναι πιο σωστό έτσι :) εκτός και αν διαφωνείς

"Choose your weapon time to play... Forget about the second day.... Choose you weapon time to go"

Με μια μικρη αλλαγή:

if ( (THISYEAR-birthYear)<0)
{

cerr << 'You can not have negative age.'<< ' Try again...' << endl;
}
else if ( (THISYEAR-birthYear)==0)
{

cerr<< 'It is imposible. You must be the youngest internet user of the world!!!'<<< 'Your name is '
<< yourName<< ' and you are approximately '<<(THISYEAR-birthYear)<< ' years old. '<< endl;
}