data reading

Write here if you have problems with your C source code

Moderator: Board moderators

Post Reply
htl
Experienced poster
Posts: 185
Joined: Fri Jun 28, 2002 12:05 pm
Location: Taipei, Taiwan

data reading

Post by htl »

I've faced many data reading problems. The ways of giving data in almost every problem are different. Especially in multi input problems, they are nightmares to me. In 469, for example, you have to analyze if the input is data part or query part. And in 10324, you have to stop the program if you get '\n' or EOF. I'm troubled with these problems. I often gets RE instead of acceptd because of the data reading. Could someone share your experience and methods? And in what book I can find these information?
10153EN
Experienced poster
Posts: 148
Joined: Sun Jan 06, 2002 2:00 am
Location: Hong Kong
Contact:

Post by 10153EN »

You can use gets.

If it's a blank line, the string get from gets is of strlen 0.
e.g. for a program runs until reading a blank line:
[c]char line[100000];
while(gets(line))
{
if(strlen(line) == 0) break;
......
}
[/c]

If it's the EOF, the gets returns NULL.
e.g. for a program runs until the EOF is read:
[c]char line[100000];
while(gets(line) != NULL)
{
......
}
[/c]

Hope can help~
htl
Experienced poster
Posts: 185
Joined: Fri Jun 28, 2002 12:05 pm
Location: Taipei, Taiwan

Post by htl »

But gets() will crash if the buffer overflow. Maybe fgets is the better way of data reading?
10153EN
Experienced poster
Posts: 148
Joined: Sun Jan 06, 2002 2:00 am
Location: Hong Kong
Contact:

Post by 10153EN »

Causing buffer overflow is the size of the string, but not choosing gets or fgets. Therefore to prevent buffer overflow, it's better to allocate an enough size of string size.
zyxw
New poster
Posts: 24
Joined: Sat Mar 22, 2008 5:49 am
Location: Chennai
Contact:

Re: data reading

Post by zyxw »

htl wrote:And in 10324, you have to stop the program if you get '\n' or EOF. I'm troubled with these problems.
The following snippet takes care of '\n' and EOF:

Code: Select all

 while(cin>>s)
 {
  // .....
 }
Post Reply

Return to “C”