Wednesday 15 September 2010

c++ - Why doesn't this loop want to work properly? -



c++ - Why doesn't this loop want to work properly? -

i've been @ hours want able add together diver , thing need show number of divers judged , average score can 1 time issue fixed.

it runs when loops around, skips city, , crashes 2nd 3rd time around. can help?

#include <iostream> #include <string> #include <sstream> using namespace std; int main(){ string name; string city; double judge[4]; double total = 0; double score; int divers = 1; int x = 0; int y = 1; do{ cout << "please come in divers name: "; getline(cin, name); cout << "enter diver's city: "; getline(cin, city); do{ cout << "enter score given justice #" << y << ": " ; cin >> judge[x]; total = total + judge[x]; y++; x++; } while(y < 6); y = 1; cout << "divers?"; cin >> divers; } while(divers == 1); cout << city << endl; cout << name << endl; cout << total << endl; cout << judge[0] << endl; cout << judge[1] << endl; cout << judge[2] << endl; cout << judge[3] << endl; cout << judge[4] << endl; system("pause"); }

when cin >> divers; end-of-line character not removed input, number leading it. then, next time inquire line std::getline() returns end-of-line character there , not wait new input.

so when cin >> drivers style input before std::getline() style input need read past end-of-line character.

one way using ignore() function:

do{ cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); cout << "please come in divers name: "; getline(cin, name); cout << "enter diver's city: "; getline(cin, city); // ...

another way utilize white-space eater std::ws in std::getline() calls:

do{ cout << "please come in divers name: "; getline(cin >> std::ws, name); cout << "enter diver's city: "; getline(cin >> std::ws, city); // ...

strictly speaking first 1 necessary. remember white-space eater eat initial spaces type getline() can't read in leading spaces if utilize technique.

c++ string loops while-loop

No comments:

Post a Comment