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

#1 jackson6612

jackson6612

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 285 posts

Posted 07 May 2011 - 06:02 PM

Hi

What's the wrong with the code? When I enter 'n' it exits fine. But when I enter 'y' or any other character the program goes crazy. Please have look at the outputs at the bottom.

// print your name n times

#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

void prntname(int dummy1, string dummy2);

int main()

{
    string name; int n; char ch;

    do
    {
        cout << "enter your name: ";
        getline (cin, name);
        cout << "how many times you want to print?: "; cin >> n;
        prntname(n, name);
        cout << endl;
        cout << "do you want to repeat?: "; cin >> ch;
    }
    while (ch != 'n');

    cout << endl;

    system("pause");

    return 0;
}

//---------------------------------------------------------
// function definition for void prntname(int dummy, string dummy)

void prntname(int dummy1, string dummy2)

{
    for (int j=1; j<=dummy1; j++)
    {
        cout << dummy2 << endl;
    }
}
//------------------------------------------------------------

Output when I enter 'n'. The program exits fine:
enter your name: jackson heights
how many times you want to print?: 10
jackson heights
jackson heights
jackson heights
jackson heights
jackson heights
jackson heights
jackson heights
jackson heights
jackson heights
jackson heights

[B]do you want to repeat?: n[/B]

Press any key to continue . . .

Output when I enter 'y' or any other character. The program goes crazy:
enter your name: jackson heights
how many times you want to print?: 10
jackson heights
jackson heights
jackson heights
jackson heights
jackson heights
jackson heights
jackson heights
jackson heights
jackson heights
jackson heights

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

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

#2 Alexander

Alexander

    YOL9

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

Posted 07 May 2011 - 07:29 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
        }

  • 0

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


#3 jackson6612

jackson6612

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 285 posts

Posted 08 May 2011 - 03:08 AM

Thanks a lot, Alexander. It works now. The amended code is given below.

Best wishes
Jackson

// print your name n times

#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

void prntname(int dummy1, string dummy2);

int main()

{
    string name; int n; char ch;

    do
    {
        cout << "enter your name: ";
        getline (cin, name);
        cout << "how many times you want to print?: "; cin >> n;
        prntname(n, name);
        cout << endl;
        cout << "do you want to repeat?: "; cin >> ch;
        cin.clear();
        while (cin.get() != '\n')
        {continue;}
    }
    while (ch != 'n');

    cout << endl;

    system("pause");

    return 0;
}

//---------------------------------------------------------
// function definition for void prntname(int dummy, string dummy)

void prntname(int dummy1, string dummy2)

{
    for (int j=1; j<=dummy1; j++)
    {
        cout << dummy2 << endl;
    }
}
//--------------------------------------------------------------

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

#4 jackson6612

jackson6612

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 285 posts

Posted 08 May 2011 - 05:01 AM

Just a quick question.

cin.clear();
while (cin.get() != '\n')
{continue;}

1: cin.clear(); : is some kind of function call to flush the buffer. Is this correct? Is there some kind of cout.clear(); too?

2: while (cin.get() != '\n') : I don't understand its purpose and function. What is cin.get? When the input buffer has been flushed, then there will be nothing left in the input stream?

3: continue; : is used to execute the loop again.

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

#5 Alexander

Alexander

    YOL9

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

Posted 08 May 2011 - 05:06 AM

cin.clear will simply clear any error flags on the cin call (i.e. goodbit, badbit, failbit, eofbit, part of iostate here) and it may be needed by your setup.

cin.get simply returns a character as an integer (which could be typecasted into a char) from the input stream, and if you retrieve all the input (i.e. until no more newlines) then that will safely flush the input stream.
  • 0

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


#6 jackson6612

jackson6612

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 285 posts

Posted 08 May 2011 - 06:48 AM

Hi once again

Isn't there some kind of single statement (function call etc.) which can be used to flush the input stream once I have done "cin >> ch;"? Please let me know? So that the "\n" doesn't get fed into the getline(). Just curious.
  • 0
I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#7 fkl

fkl

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 417 posts

Posted 08 May 2011 - 01:26 PM

use cin.ignore(); right after the cin statement in your program.

Just verified and it works with your current program. Though what Alexander suggested above is more comprehensive treatment and handles as many newlines characters as we insert.
  • 0

#8 jackson6612

jackson6612

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 285 posts

Posted 08 May 2011 - 01:43 PM

use cin.ignore(); right after the cin statement in your program.

Just verified and it works with your current program. Though what Alexander suggested above is more comprehensive treatment and handles as many newlines characters as we insert.


Thanks a lot, fayyazlodhi. Indeed it works.

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

#9 Alexander

Alexander

    YOL9

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

Posted 08 May 2011 - 07:45 PM

If you enter a string or in some cases a character, cin.ignore will be incorrect and eat valid input (i.e. "do you want to try again"), you would have to know when and where cin.ignore is valid, this is why I gave a general solution (albeit another thing to remember each time you use input like that).
  • 0

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


#10 jackson6612

jackson6612

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 285 posts

Posted 09 May 2011 - 09:40 AM

If you enter a string or in some cases a character, cin.ignore will be incorrect and eat valid input (i.e. "do you want to try again"), you would have to know when and where cin.ignore is valid, this is why I gave a general solution (albeit another thing to remember each time you use input like that).


Thanks for the input, Alexander. Of course, your solution was more general and comprehensive ( as is also said by fayyazlodhi). The only problem with my original code was that "/n" was automatically left in the input stream and then later fed to getline(), as you told me.

Your solution does flush the buffer but then it doesn't matter if I enter a character (such as 'y', '9') or a string (such as 'yy', '99') for "do you want to repeat?:". The cin will accept anything except "\n". Although according to my initial declaration I wanted the user only to enter a character as reply to "do you want to repeat?". Your solution makes that declaration 'wrong'. (Perhaps "wrong" is not the right word here - I'm not a native English so please excuse if it's improper).

I was only concerned with emptying the input stream of "\n" which automatically gets fed into when I press enter.

Do I make any sense? For a person like me who has limited understanding of programming simple and straightforward things are preferable. Please do let me know if what I say is wrong. Thank you.

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

#11 Alexander

Alexander

    YOL9

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

Posted 09 May 2011 - 09:54 AM

Your speculation is correct, although the code performs as written. When you enter "yy", cin will only take the first character (as you have written) and store it in to ch. You cannot really prevent the user from typing a string, you can only take what you need out of it.

Edited by Alexander, 09 May 2011 - 11:10 AM.
revised

  • 0

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


#12 jackson6612

jackson6612

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 285 posts

Posted 09 May 2011 - 10:36 AM

Your speculation is correct, although the code performs as written. When you enter "yy", cin will only take the first character (as you have written) and store it in to ch. The other "y" will remain in the input buffer - my code will not remove the other y, only newlines. You cannot really prevent the user from typing a string, you can only take what you need out of it.


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?:

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





Also tagged with one or more of these keywords: loop

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