c++ - why its jumping out of program? -
i start learning c++.
when execute code it's jumping out of program without error. why?
#include "stdafx.h" #include <iostream> using namespace std; int _tmain(int argc, _tchar* argv[]) { char s1[20],s2[10]; cout<<" enter number : "; cin.get(s1,19); cout<<" enter number : "; cin.get(s2,9); cout<<s1<<"/n"<<s2; getch(); }
the method get() reads upto '\n' character not extract it.
so if type: 122345<enter>
line:
cin.get(s1,19); will read 12345, '\n' (created hitting <enter>) left on input stream. next line read:
cin.get(s2,9); will read nothing sees '\n' , stops. not extract '\n' either. input stream still has '\n' there. line:
getch(); just reads '\n' character input stream. allows finish processing , exit program normally.
ok. happening. there more this. should not using get() read formatted input. use operator >> read formatted data correct type.
int main() { int x; std::cin >> x; // reads number x // error if input stream not contain number. } because std::cin buffered stream data not sent program until push <enter> , stream flushed. useful read text (from user input) line @ time parse line independently. allows check last user input errors (on line line bases , reject if there errors).
int main() { bool inputgood = false; { std::string line; std::getline(std::cin, line); // read user line (throws away '\n') std::stringstream data(line); int x; data >> x; // reads integer line. // if input not number data set // error mode (note std::cin in example // 1 above). inputgood = data.good(); } while(!inputgood); // force user input again if there error. } if want advanced can @ boost libs. provide nice code in general , c++ program should know contents of boost. can re-write above as:
int main() { bool inputgood = false; { try { std::string line; std::getline(std::cin, line); // read user line (throws away '\n') int x = boost::lexical_cast<int>(line); inputgood = true; // if here lexical_cast worked. } catch(...) { /* throw away lexical_cast exception. forcing loop */ } } while(!inputgood); // force user input again if there error. }
Comments
Post a Comment