If you are a beginner, you will find it very unusual sometime regarding taking inputs. Some problems will say, "The Program will continue till the END OF FILE:, some will say "Stop taking input if N=0" etc etc. Some important ways to take input will be described here:
1. If you are said to take an integer number (n) as input till the End Of File/ (EOF):
int main(){
int n;
while(scanf("%d", &n)!=EOF){
...........
...........
}
return 0;
}
return 0;
}
or, If there is nothing said in the problem description about how long you will take the inputs, in that case you also have to follow this way.
2. If you are said to take an integer number n and it is said that the end of input will be indicated by a case with n=0:
int n;
while(1){
scanf("%d", &n);
if(n==0)
break;
........
........
}
3. If the problem statement says something like "The input can contain different test cases. The first line of the input indicates the number of test cases. For each test case take an integer number input" :
int n, test;
scanf("%d", &test);
while(test--){
scanf("%d", &n);
................
................
}
4. In the previous input technique, after taking the input of test, if it was said to take a string (char str[100]) as input then we would had done that as below:
int test;
char str[100], dummy;
scanf("%d", &test);
dummy= getchar();
while(test--){
gets(str);
................
................
}
As "str" is a string, after giving the input of test when we press the enter button, str takes that as the input, which creates big problem while processing. Thats why another character variable dummy is used right after taking the input to the test variable.
5. Some rare use of scanf and printf:
(i)
scanf("%[ABCDEFGHIJKLMNOPQRSTUVWXYZ]",&line); //line is a string
This scanf() function takes only uppercase letters as input to line and any other characters other than A..Z terminates the string.
(ii)
scanf("%[^\n]",line); //line is a string
The above scanf() will behave like gets().
6.If the problem statement says to take a set of characters as input till the end of file:
char str[100];
int main(){
while(gets(str)!=NULL){
.......
.......
}
return 0;
}
6.If the problem statement says to take a set of characters as input till the end of file:
char str[100];
int main(){
while(gets(str)!=NULL){
.......
.......
}
return 0;
}
No comments:
Post a Comment