Jump to content

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

- - - - -

  • Please log in to reply
21 replies to this topic

#1
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
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]


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

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
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
        }

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#3
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
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;

    }

}

//--------------------------------------------------------------


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

#4
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
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.
I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#5
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
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.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#6
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
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.
I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#7
fayyazlodhi

fayyazlodhi

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 403 posts
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.

#8
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts

fayyazlodhi said:

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
I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#9
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
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).
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#10
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts

Alexander said:

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
I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#11
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
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

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#12
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts

Alexander said:

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


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




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users