قُلْ إِنَّ صَلَاتِي وَنُسُكِي وَمَحْيَايَ وَمَمَاتِي لِلَّـهِ رَبِّ الْعَالَمِينَ - الأنعام: ١٦٢

Monday, September 28, 2009

Detecting the "Enter" key

السلام عليكم و رحمة الله و بركاته

This is a short post.
almost a year ago, I tried to solve a problem on the UVa and i got it "Time limit exceeded". I knew before submitting that it won't be accepted, as i didn't know how to detect the "Enter" key press and it was needed as a stop condition for the first loop :D

anyway, here we go
if you are trying to use "cin" then you'll not be able to detect the new line.
when debugging, u may enter 10 new lines & then a value...i mean it will wait for the value and won't consider the new lines!

you may go to a lower level
if(cin.get() == '\n')
but that's when u are expecting the enter to be pressed
as it reads 1 char only

or u can use "cin.getline()"
and then check for the string's length
if == 0 then "Enter" is pressed
That's useful when u r expecting a mix of strings & enters


sources:
ACMaa Magdi (thanks :))

4 comments:

  1. eh da, mesh momken, my name is on TV again :D. howa kol el nas ba2et betekteb my name in their blogs walla eh :D.

    It's an honor ya fandem :). And, detecting Enter, it was a problem for me before, at the beginning. I don't like cin.getline() very much, and I have the feeling that she doesn't like me either :D. But what can we do. Life forces us to use things we may not like very much :P.

    I hope you solve all enter-detecting-related problems b2a ;) No more excuses :huh

    Thanks NN :)

    ReplyDelete
  2. yess ya ACMaa enty mashhooora :huh

    lol, i don't wanna use c++ aslan :D
    and probably will be using it in my GP :D...Rabena yostor ba2a :D

    I hope i solve this problem el awel :D still moktane3a that it should be AC :huh

    Thanks leeky enty begad :) (f)

    ReplyDelete
  3. cin.getline(); :):)
    really it is great sol and the fantastic thing its simplicity :D:D
    big thanks noran and ACMaa :) :X

    when I think about this problem I have a great sol bardo :$:$:D:D:P:P
    this is mine but no one laugh at mee :D:D:D ( note el5ia tobarir el wasila :D:P)

    string str;
    string x;
    int count =0;
    while ( str != "\n")
    {
    str = getchar();
    x += str;
    if ( str == "\n" && count ==0)
    cout <<"el 7amed llah This is enter :D";

    count ++;
    }


    cout << x;

    ReplyDelete
  4. very cool Daliash ;)

    ana moktane3a bardo bekesset "el 3'aya tobarer el waseela" when it comes to el codes el gameela :D

    i do this a lot B-)
    Thanks for sharing ur idea :)

    ReplyDelete