Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

using user-defined function, do/while loop, to print name

loop

  • Please log in to reply
21 replies to this topic

#13 fkl

fkl

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 417 posts

Posted 09 May 2011 - 10:49 AM

I understand your point Jackson as well as that of Alexander.

I have been using this to clear up buffer i.e. the scenario usually was that i was reading an integer using cin from a file or standard input, followed by a gets reading a string as a complete line, which used to always cause problems like you have mentioned above. In that scenario, i KNEW there is never going to be more than a single character issue, so i can pass on the flaws rightfully highlighted by Alexander.

Yet another function i have been using was fflush

#include <stdio.h>

char input[50];
...
printf("Enter input: ");
fflush(stdout);
gets(input);

Hope that helps

Edit: I didn't read the last two posts by you guys when i was writing
  • 0

#14 fkl

fkl

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 417 posts

Posted 09 May 2011 - 11:07 AM

Thanks for the confirmation, Alexander. But I'm now more confused!:confused: Please have a look on the code below. You see I entered "yy" to cin. If only one "y" is accepted and the other is left in the input stream, then where does that remaining "y" go? If it is there in the input stream, then when I input "jack dawson" to "enter your name:", it should go with the "jack dawson", and perhaps I should get something like "yjack dawson".

I was supposed to enter an integer to "how many times you want to print: " because of initial declaration. But you see before entering "5" I pressed "enter" button several times which is equivalent to a character. So, I was expecting the program to go little crazy when I entered wrong type of data in the input stream. How did it preserve its sanity?

Please help me with these queries. Thanks a lot.

Output:

enter your name: jack dawson
how many times you want to print?: 5
jack dawson
jack dawson
jack dawson
jack dawson
jack dawson

do you want to repeat?: [B][COLOR="red"]yy[/COLOR][/B]
enter your name: jack dawson
how many times you want to print?: 5
jack dawson
jack dawson
jack dawson
jack dawson
jack dawson

do you want to repeat?: y
enter your name: jack dawson
[U]how many times you want to print?:[/U]



[B][COLOR="red"]5[/COLOR][/B]
jack dawson
jack dawson
jack dawson
jack dawson
jack dawson

do you want to repeat?:


Here is what i have been doing to have better control over the input no matter what is typed on the screen - was to use,

cin.getline(buffer, size, '\n');

Even when i needed input in an integer. In above scenario no matter what the user types, you can input the whole line, discard what is not needed i.e. i used strtok to split the string at the first space, and convert that part into an integer using atoi().

The above call can be put in a while loop test condition and it would work well whether 'y' or 'yy' or any thing else. All it picks up is a new line (or what ever line terminator we tell it to have) as long as the line length is with in the bounds.

What do you guys think? Alexander?
  • 0

#15 fkl

fkl

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 417 posts

Posted 09 May 2011 - 11:10 AM

I remember this when i used to take part in timed programming competitions at universities as a BS student and there were always tricky malicious input in the judge's large test files i.e. unexpected spaces, new lines, unwanted characters and what not - just to make your program go haywire. cin.getline used to get us through that although parsing a mix of integers and string after having used getline required a little more coding effort :)
  • 0

#16 Alexander

Alexander

    YOL9

  • Moderator
  • 3963 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 09 May 2011 - 11:24 AM

cin.get should actually consume all characters it reads, so naturally the first y is extracted, the second is consumed and the newline is consumed and then the loop ends cleaning the input buffer of any lingering text for the next iteration.

This is all I can really say for that, I do not understand the mess that C++ gives for input. Your only real solution would be to grab all the remaining input (fgets in C, cin.getline in C++) and then parse it with something such as sscanf which should return valid tokens parsed, so you can validate input. I've no clue what C++ provides for this, I do not even think it does provide anything (it is not my native language)

So I agree with where Fayyaz was going with this.

  • 0

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.


#17 fkl

fkl

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 417 posts

Posted 09 May 2011 - 11:34 AM

C++ does provide strtok() where we can specify a list of delimiters (space, comma etc.) but it is not thread safe though there are gcc/++ specific strtok_r() (re entrant versions).

Moreover, like you mentioned using sscanf, which can be formatted with something like "%[abcedef]s %[3232]d" to ensure our stream only takes what it's format allows and nothing else. This is the best i know c/c++ can get and i strongly agree that it does create a mess being so many functions and not all with a reason to exist.
  • 0

#18 jackson6612

jackson6612

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 285 posts

Posted 12 May 2011 - 05:57 AM

Thanks a lot, Fayyaz, Alexander. I won't post any follow-on questions related to the previous posts by both of you because I don't wan to confuse myself! :) You better keep talking to each other. :) I genuinely appreciate the help I received.

With best regards
Jackson
  • 0
I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#19 fkl

fkl

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 417 posts

Posted 12 May 2011 - 12:10 PM

My apologies if i had caused any confusion Jackson. I was only trying to add what i know and at the same time i learned a few new things from Alexander.

You are welcome to clarify any thing you have in mind. That is the precise intention of this forum.

Edited by fayyazlodhi, 12 May 2011 - 12:11 PM.
spelling mistake

  • 0

#20 jackson6612

jackson6612

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 285 posts

Posted 12 May 2011 - 02:21 PM

My apologies if i had caused any confusion Jackson. I was only trying to add what i know and at the same time i learned a few new things from Alexander.

You are welcome to clarify any thing you have in mind. That is the precise intention of this forum.


Not at all, no need for apologies. I was simply trying to say that I won't pursue the topic any further because my limited knowledge will only lead me to more confusion. I have my mid-term exam next week, so I must focus on that for now. It's because of you, Alexander, and many other nice and helpful people here that I understand the programming a little bit, otherwise my PhD instructor really sucks. He always gives me the impression that education doesn't do good to everyone!

With best regards
Jackson
  • 0
I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#21 jackson6612

jackson6612

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 285 posts

Posted 11 June 2011 - 03:25 PM

If you accept an number (integer, float, double) or char type with cin then you are left with a newline in the input stream. As cin.ignore would eat valid characters, you could certainly just eat a single newline afterwards:

cout << "do you want to repeat?: "; cin >> ch;
        cin.clear(); //clear flag state
        while (cin.get() != '\n') {
          continue; //continue to check for newlines in input
        }


Hi again

I'm so sorry for bringing this up again. :( But I think I didn't really understand it well.

Please have a look on the code and its output at the end. After every cin "\n" is left behind in the input stream. You see once I have CINed "jackson", the line "hello, how are you" gets displayed on a new line. Why is so? I didn't do anything to achieve that. I suspect it's because of that "\n" character left behind after I pressed ENTER key. What doesn't it really mean? That means "\n" which was left behind has been used. Am I correct so far?

Now I'm returning to the code in my first post. If that 'automatically' generated "\n" has been used to display the next "COUT" on a new line, then what does getline (cin, name) keep on eating? "\n" has already been consumed!

// understanding_newline char_left_input.cpp
// understanding the "\n" left in the input stream

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

int main()
{
        int i; string name;

        for (i=0; i<4; i++)
        {
                cout << "hello, how are you\n";
                cout << "i'm fine\n";
                cout << "what's going on these days?\n";
                cout << "sorry, i forgot your name.\n";
                cout << "what's your name?\n";
                cout << "my name is: "; cin >> name;
        }

        system("pause");
        return 0;
}


OUTPUT
hello, how are you
i'm fine
what's going on these days?
sorry, i forgot your name.
what's your name?
my name is: [B][COLOR="lime"]jackson[/COLOR][/B]
[COLOR="lime"]hello, how are you[/COLOR]
i'm fine
what's going on these days?
sorry, i forgot your name.
what's your name?
my name is:

  • 0
I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#22 Alexander

Alexander

    YOL9

  • Moderator
  • 3963 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 11 June 2011 - 06:46 PM

The console will only display, not consume. If you type enter, it is both displayed on the console as a newline, but also part of the string.

Imagine if your console was incapable if displaying newlines, you would see:
my name is: jackson□Hello, how are you
(hopefully the square appears)

This would look strange to you, as you have typed enter. But you do see that the newline (in this case represented as □ by me) is still in the input as you see, just like "jackson" is in the input still. The console simply can't represent the newline as a character, so it goes down a line, and also initiates the program to send the next output (the cout)

I hope this is clear, feel free to ask more.
  • 0

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.






Also tagged with one or more of these keywords: loop

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download