我正在尝试有效地阅读stdin
通过使用setvbuf
在`_IOFBF~模式下。我是缓冲新手。我在寻找working例子。
输入以两个整数开始(n
,k
)。下一个n
输入行包含 1 个整数。目的是打印有多少个整数可以被整除k
.
#define BUFSIZE 32
int main(){
int n, k, tmp, ans=0, i, j;
char buf[BUFSIZE+1] = {'0'};
setvbuf(stdin, (char*)NULL, _IONBF, 0);
scanf("%d%d\n", &n, &k);
while(n>0 && fread(buf, (size_t)1, (size_t)BUFSIZE, stdin)){
i=0; j=0;
while(n>0 && sscanf(buf+j, "%d%n", &tmp, &i)){
//printf("tmp %d - scan %d\n",tmp,i); //for debugging
if(tmp%k==0) ++ans;
j += i; //increment the position where sscanf should read from
--n;
}
}
printf("%d", ans);
return 0;
}
问题是如果数字位于边界处,则buffer buf
会读23
from 2354\n
,当它应该读取时2354
(这是不可能的)或者什么都没有。
我该如何解决这个问题?
Edit
现已解决(有分析).
Edit
完整的问题说明