ผลต่างระหว่างรุ่นของ "Adt lab/notes on how to read input"

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
(หน้าที่ถูกสร้างด้วย ': ''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 ...')
 
 
(ไม่แสดง 1 รุ่นระหว่างกลางโดยผู้ใช้คนเดียวกัน)
แถว 3: แถว 3:
 
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.
 
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 <tt>cin.eof</tt> 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.
 
In C++, you can use <tt>cin.eof</tt> 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.
  
แถว 20: แถว 21:
 
     work(i,j);
 
     work(i,j);
 
   }
 
   }
 +
}
 +
</source>
 +
 +
== 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>
 
</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);
}