Re: Text Input manipulation
From: B. v Ingen Schenau (bart_at_ingen.ddns.info)
Date: 11/11/03
- Next message: Digital Puer: "Re: small projects to learn STL?"
- Previous message: Ali R.: "Re: GUI Builder in C++ .Net vs. MFC or VB?"
- In reply to: Silver: "Text Input manipulation"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 11 Nov 2003 18:29:09 +0100
Silver wrote:
> Hi everyone,
>
> I am writing a program where one is supposed to enter a number a 'student'
> objects and define the 'name' , 'number' and 'grade' of each student.
> Well, I got a working program, but I have a question. I want to force the
> program to only allow 30 character names for the 'student name'. The
> student name in entered through cin.getline(name, 30, '\n'). How can I
> make sure, that if more than 30 characters are entered, they will be
> ignored without affecting the program?? Because now, when I tried to enter
> more than 30 characters, I couldn't enter the student's 'number' and
> 'grade', possibly because of the extra characters.
> My code is as follows:
>
> class A
> {
> private:
> static const int MAX = 30;
> char name[MAX];
> int aem;
> int grade;
> public:
> void setName();
> void setAem(int n);
> void setGrade(int m);
> // accessors
> void GetName();
> int GetAem();
> int GetGrade();
> };
>
> void A::setName()
> {
> cin.ignore();
> cin.getline(name, 30, '\n');
Because getline reads the terminating newline (\n), but does not store it,
there is no easy way to tell if there is more input to read (and discard).
As an alternative, you can use cin.get() followed by a call to cin.ignore():
cin.get(name, 30, '\n');
cin.ignore(INT_MAX, '\n');
This will read up to 30 characters into name and discard the rest of the
line.
> }
>
Bart v Ingen Schenau
-- a.c.l.l.c-c++ FAQ: http://www.snurse-l.org/acllc-c++/faq.html a.c.l.l.c-c++ FAQ mirror: http://nullptr.merseine.nu:8080/acllcc++.html c.l.c FAQ: http://www.eskimo.com/~scs/C-faq/top.html c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/
- Next message: Digital Puer: "Re: small projects to learn STL?"
- Previous message: Ali R.: "Re: GUI Builder in C++ .Net vs. MFC or VB?"
- In reply to: Silver: "Text Input manipulation"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|