ผลต่างระหว่างรุ่นของ "Adt lab/notes on how to read input"
ไปยังการนำทาง
ไปยังการค้นหา
Jittat (คุย | มีส่วนร่วม) |
Jittat (คุย | มีส่วนร่วม) |
||
แถว 25: | แถว 25: | ||
== Using scanf == | == Using scanf == | ||
+ | <source lang="c"> | ||
+ | #include <cstdio> | ||
+ | |||
+ | main() | ||
+ | { | ||
+ | int x,y; | ||
+ | do { | ||
+ | int r = scanf("%d %d",&x,&y); | ||
+ | if(r!=2) { | ||
+ | break; | ||
+ | } | ||
+ | printf("%d\n",x+y); | ||
+ | } while(true); | ||
+ | } | ||
+ | </source> |
รุ่นแก้ไขปัจจุบันเมื่อ 07:03, 9 กุมภาพันธ์ 2559
- This is part of adt lab.
In many ICPC tasks, the input may not specify the number of test cases. In that case, you need to check for the end-of-file (EOF) mark youself.
Using cin
In C++, you can use cin.eof to check that. However, it only works when you reach the end-of-file. Sometimes, you read everything, but you are not at the end of file, so you have to also check again after you attempt to read pass the EOF.
You can see the code below which is for the task 3n+1.
main()
{
while(!cin.eof()) {
int i,j;
cin >> i;
if(cin.eof()) {
break;
}
cin >> j;
work(i,j);
}
}
Using scanf
#include <cstdio>
main()
{
int x,y;
do {
int r = scanf("%d %d",&x,&y);
if(r!=2) {
break;
}
printf("%d\n",x+y);
} while(true);
}