Re: Text Input manipulation

From: B. v Ingen Schenau (bart_at_ingen.ddns.info)
Date: 11/11/03


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/


Relevant Pages

  • Re: malloc for members of a structure and a segmentation fault
    ... almost the entire FAQ, but can't seem to figure out this problem. ... and a pointer to a character pointer */ ... int main { ... void test; ...
    (comp.lang.c)
  • Re: without loop printing 1 to n
    ... int main ... void printrange ... from any other external name in the first six characters. ... underscore after the fifth character of this function name, ...
    (comp.lang.c)
  • Re: faq & casting malloc()
    ... > void f ... int main ... The FAQ http://www.eskimo.com/~scs/C-faq/q7.6.html talks about the correct ... history of why code had previously cast the result of malloc but again, ...
    (comp.lang.c)
  • Re: Help with a progam
    ... > int main(void) ... > allocate enough memory to get all the characters in the file. ... If you insist on reading the file into memory first (rather than using ...
    (comp.lang.c)
  • Re: Interchanging variables between functions
    ... Roberto Dias wrote: ... void Add_Ten(unsigned int * p_num) ... C++ Faq: http://www.parashift.com/c++-faq-lite C Faq: http://www.eskimo.com/~scs/c-faq/top.html alt.comp.lang.learn.c-c++ faq: ...
    (comp.lang.cpp)