Clearing Buffer

This is a discussion on Clearing Buffer within the C++ Programming forums, part of the General Programming Boards category; ok im trying to write a program using 2 Char Arrays of about size 10, and i want the first ...

  1. #1
    Fallen AndyBomstad's Avatar
    Join Date
    Jan 2005
    Posts
    52

    New Problem

    ok im trying to write a program using 2 Char Arrays of about size 10, and i want the first to be a users first name and the 2nd to be their last

    once they enter both first and last i want it to desplay like this:

    BUCKET #0 = A
    BUCKET #1 = N
    BUCKET #2 = D
    BUCKET #3 = Y

    BUCKET #0 = B
    BUCKET #1 = O
    BUCKET #2 = M
    BUCKET #3 = S
    BUCKET #4 = T
    BUCKET #5 = A
    BUCKET #6 = D

    i do NOT want it to show up like this :

    BUCKET #0 = A
    BUCKET #1 = N
    BUCKET #2 = D
    BUCKET #3 = Y
    BUCKET #4 =
    BUCKET #5 =
    BUCKET #6 =
    BUCKET #7 =
    BUCKET #8 =
    BUCKET #9 =

    BUCKET #0 = B
    BUCKET #1 = O
    BUCKET #2 = M
    BUCKET #3 = S
    BUCKET #4 = T
    BUCKET #5 = A
    BUCKET #6 = D
    BUCKET #7 =
    BUCKET #8 =
    BUCKET #9 =


    the following code will display this :

    BUCKET #0 = A
    BUCKET #1 = N
    BUCKET #2 = D
    BUCKET #3 = Y
    BUCKET #4 =
    BUCKET #5 =
    BUCKET #6 =
    BUCKET #7 =
    BUCKET #8 =
    BUCKET #9 =
    press any key to continue....

    And Nothing more, it doesnt even show the last name....
    Code:
    #include<iostream>
    using namespace std;
    
    int main()
    {
        char first[10];
        char last[10];
        int i = 0 ;
        cout<<"Please Enter Your First Name: ";
        cin>>first;
        cout<<"Please Enter Your Last Name: ";
        cin>>last;
        while(i <= 9)
        {
                
                cout<<endl<<"Bucket #"<<i<<" = "<<first[i]<<endl;
                i++;
        }
        while(i <= 9)
        {
                
                cout<<endl<<"Bucket #"<<i<<" = "<<last[i]<<endl;
                i++;              
        }
        system("pause");
    }
    and i know its somthing with the input buffer or checking to see if it found the EOF, but i dont know how to go about doing this
    Last edited by AndyBomstad; 04-27-2005 at 12:23 PM.

  2. #2
    Registered User
    Join Date
    Mar 2005
    Posts
    140
    the reason your second loop does nothing is becuase you don't reset i

    also, look into strlen() instead of always comparing <= 9
    Last edited by spydoor; 04-27-2005 at 01:24 PM.

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,794
    Code:
    const int maxlen = 10;
    char first[maxlen];
    char last[maxlen];
    ...
    while(i < maxlen && first[i ] != '\0')
    {
        ...
    }
    i = 0;
    while(i < maxlen && last[i ] != '\0')
    {
        ...
    }
    You might also want to consider using cin's get member function to limit how many characters the user can enter so you don't accidentaly overwrite some memory.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Cheesy Poofs! PJYelton's Avatar
    Join Date
    Sep 2002
    Location
    Boulder
    Posts
    1,728
    You can avoid printing empty spots if you changed your while loop to something like this:
    Code:
       while(first[i]!='\0')

  5. #5
    Super Moderater.
    Join Date
    Jan 2005
    Posts
    374
    Enjoy

    Code:
    #include<iostream>
    #include<string>
    using namespace std;
    
    int main()
    {
        char first[10];
        char last[10];
        int i = 0 ;
        int j=0;
        cout<<"Please Enter Your First Name: ";
        cin>>first;
        int size_first=strlen(first);
        cout<<"Please Enter Your Last Name: ";
        cin>>last;
        int size_last=strlen(last);
        while(i < size_first)
        {
                
                cout<<endl<<"Bucket #"<<i<<" = "<<first[i]<<endl;
                i++;
        }
        while(j < size_last)
        {
                
                cout<<endl<<"Bucket #"<<j<<" = "<<last[j]<<endl;
                j++;              
        }
        system("pause");
    }

  6. #6
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Hi,

    When you create an array like this:

    char first[10];

    it's filled with junk characters. The fact that you got blank output after the name that was stored in that array was luck--the chars in the array after the name could have been anything.

    In addition, strlen() won't necessarily work on an array like that. All <cstring> functions like strlen() rely on a '\0' character marking the end of the letters in the char array. If strlen() works, it's because there just happened to be a '\0' character at the end of the name, but you can't count on that.

    Instead, when you are getting input from the user and you want to put it into a char array, you can do this:

    char last[10];
    cout<<"Please Enter Your First Name: ";

    cin.ignore(1);
    cin.getline(last, 10);


    In that statement, getline() will read in input up to a maximum of 9 characters. It then automatically puts a '\0' after the last char read in. If getline() only reads in 4 chars, then the 5th char will be a '\0'. If the user inputs 20 chars, then getline() will only read in 9 chars, and it will enter a '\0' in the last spot in the array. Subsequently, you will be able to use all the <cstring> functions like strlen() on the array. strlen() will give you the number of chars that were stored in the array, which you can use in your loop.
    Last edited by 7stud; 04-28-2005 at 03:32 AM.

  7. #7
    0x01
    Join Date
    Sep 2001
    Posts
    88

    safeGet()

    Code:
    #include <iostream>
    #include <conio.h> // getch()
    
    using namespace std;
    
    int safeGet(char *buffer, unsigned short len)
    {
    	const char BACKSPACE	= 0x08;
    	const char ENTER	= 0x0D;
    
    	char keyPressed = NULL;
    	unsigned short idx = 0;
    
    	memset(buffer, '\0', sizeof(buffer));
    
    	do
    	{
    		keyPressed = getch();
    
    		switch (keyPressed)
    		{
    		case BACKSPACE:
    			{
    				if (idx > 0)
    				{
    					buffer[idx - 1] = '\0';
    					cout << "\b" << ends << "\b" << flush;
    
    					idx -= 1;
    				}
    				break;
    			}
    		case ENTER:
    			{
    				
    				buffer[idx] = '\0';
    				break;
    			}
    		default:
    			{
    				if (idx < (len-1))
    				{
    					buffer[idx] = keyPressed;
    					putchar(buffer[idx]);
    
    					idx += 1;
    				}
    				break;
    			}
    		}
    
    	}
    	while (keyPressed != ENTER);
    
    	cout << endl;
    
    	return idx; // if your paranoid
    }
    
    ///
    
    int main()
    {
    	const unsigned short MAX = 10;
    
    	char* fname = new char[MAX];
    	char* lname = new char[MAX];
    
    	cout << "FNAME:" << ends;
    	safeGet(fname, MAX);
    
    	cout << "LNAME:" << ends;
    	safeGet(lname, MAX);
    
    	cout << endl; // seperate
    
    	for (int idx = 0; idx < strlen(fname); idx++)
    		cout << " fname[" << idx << "] \t= " << fname[idx] << endl;
    
    	cout << endl; // seperate
    
    	for (idx = 0; idx < strlen(lname); idx++)
    		cout << " lname[" << idx << "] \t= " << lname[idx] << endl;
    
    	delete[] fname;
    	delete[] lname;
    
    	return 0;
    }
    Last edited by knave; 04-28-2005 at 09:01 PM.

  8. #8
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,422
    > memset(buffer, '\0', sizeof(buffer));
    Oh dear,
    Go read a book on how sizeof works on pointers.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  9. #9
    0x01
    Join Date
    Sep 2001
    Posts
    88

    No need for sarcasm.

    > memset(buffer, '\0', sizeof(buffer));
    Oh dear,
    Go read a book on how sizeof works on pointers.
    sizeof on a pointer will only return 4 bytes on an x86 (depends). Because its just a "pointer."

    Thus,
    Code:
    {
            ...
            memset(buffer, '\0', sizeof(buffer));
            ...
    }
    would not work they way I intended it to. It was a mistake.

    You could...
    Create a for loop based on 'len' in safeGet() to assign the element n of buffer = '\0';

    ///

    > memset(buffer, '\0', sizeof(buffer));
    Oh dear,
    Go read a book on how sizeof works on pointers.
    This sounds like a semi-flame, because of what little you said.(?) You could have elaborated on why sizeof(a_pointer) is incorrect. Your post is equivalent to "Look, I'm smarter than knave!" Spare "us" from your "oh dear," sarcasm.

    If it was a flame. Then, Salem... ***k you.
    Last edited by knave; 04-29-2005 at 09:55 PM.

  10. #10
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >Your post is equivalent to "Look, I'm smarter than knave!"
    And your code contains some other mistakes besides the one Salem pointed out.

  11. #11
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,422
    Well since there are perfectly usable standard ways of reading a line (which are also safe), your post seemed entirely pointless.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  12. #12
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Hi,

    Instead, when you are getting input from the user and you want to put it into a char array, you can do this:

    Code:
    char last[10];
    cout<<"Please Enter Your First Name: ";
    
    cin.ignore(1); 
    cin.getline(last, 10);
    I just wanted to point out an error in my code. I debated about whether to put that line in there because the reason involves a lengthy explantaion of how cin>> and getline() interact in the same program, which can cause errors. But, if there is no line with cin>> on it before the cin.getline(), then ignore(1) will skip the first letter of the user's input. Hopefully, you will be replacing all your cin>> lines with cin.getline(), and in that case ignore(1) wouldn't be needed.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Proper method of clearing buffer
    By Oldman47 in forum C++ Programming
    Replies: 14
    Last Post: 04-23-2007, 07:14 PM
  2. Replies: 16
    Last Post: 10-29-2006, 04:04 AM
  3. Clearing input buffer after using getch()
    By milkydoo in forum C++ Programming
    Replies: 3
    Last Post: 07-21-2003, 11:04 PM
  4. text input buffer clearing
    By red_Marvin in forum C++ Programming
    Replies: 4
    Last Post: 03-20-2003, 02:17 PM
  5. Console Screen Buffer
    By GaPe in forum Windows Programming
    Replies: 0
    Last Post: 02-06-2003, 04:15 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21