1 / 3
Mar 2012

Read This:
en.wikipedia.org/wiki/Newline6

This is a community. The test input files for a single problem could be created by multiple people. This means that there may be mixed methods of newline characters in the same problemset.

Therefore, if you are using getchar, make sure that you are using it as part of a method that will not have issues with this.

Example Input File:

2
the quick brown fox
jumped over the lazy dog

This is not good:

#include <cstdio>
using namespace std;
int main()
{
	int t;
	char s[50],c;
	scanf("%d", &t);
	getchar();
	while(t--)
	{
		gets(s);
		printf("%s\n", s);
	}
	return 0;
}

Depending on what architecture the input file is created on, you may get both lines outputted, or if the newline is "\r\n", then the code will output one blank line and the first line of the input.

A better idea is this:

#include <cstdio>
using namespace std;
int main()
{
	int t;
	char s[50];
	scanf("%d", &t);
	gets(s);
	while(t--)
	{
		gets(s);
		printf("%s\n", s);
	}
	return 0;
}

Regardless of what type of newline is used, this will work.

Cheers,
Leppy

  • created

    Mar '12
  • last reply

    Dec '14
  • 2

    replies

  • 1.8k

    views

  • 2

    users

  • 1

    link

2 years later

How do you use this if the problem requires constant input (for exapmle until n==0) ?

12 days later

Well in general I would suggest using scanf if you're dealing with integer types.

#include <cstdio>
using namespace std;
int main()
{
	int n;
	scanf("%d", &n);
	while(n != 0)
	{
		// do stuff with n  
		printf("%d\n", n);
		scanf("%d", &n);
	}
	return 0;
}