请告诉我每次循环输入时如何正确使用fgets。由于我的for循环只工作一次然后程序中断。我也尝试过使用buffer和getc,但似乎没什么用。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
int k,i,j,t,n,m;
char buffer[100];
fgets(buffer,100,stdin);
sscanf(buffer,"%d",&t);
while(t--){
char buffer1[100];
fgets(buffer1,100,stdin);
sscanf(buffer1,"%d%d",&n,&m);
char pattern[n+1][m+1];
for(i=0;i<n;i++){
fgets(pattern[i],m,stdin);
}
}
}
/* My OUTPUT:
2
2 3
RGR
GRR
3 4
Process returned 0 (0x0) execution time : 8.106 s
Press any key to continue.
where as I wanted this:
2
2 3
RGR (this is just random input
GRR )
3 4
RRGG (this is just random input
GRRR
RGGG )
*/
答案 0 :(得分:0)
你仍然没有足够的防守功能,所以如果它们中的任何一个失败你就可以抓住它。我会说检查函数的返回值和几个关于函数中使用的参数的检查。
#include<stdio.h>
#include<stdlib.h>
int main(void){
int t;
char buffer[100];
if( fgets(buffer,100,stdin) == NULL ){
fprintf(stderr, "%s\n", "Input Error using fgets");
exit(1);
}
if( sscanf(buffer,"%d",&t) != 1){
fprintf(stderr, "%s\n", "Input Error using sscanf");
exit(1);
}
if( t < 0 ){
fprintf(stderr, "%s\n","Error in inputting t" );
exit(1);
}
while(t--){
char buffer1[100];
if( fgets(buffer,100,stdin) == NULL ){
fprintf(stderr, "%s\n", "Input Error using fgets");
exit(1);
}
int n,m;
if( sscanf(buffer1,"%d%d",&n,&m) == 2){
fprintf(stderr, "%s\n", "Input Error using sscanf");
exit(1);
}
if(!( n && m) ){
fprintf(stderr, "%s\n", "Error in input n,m" );
exit(1);
}
char pattern[n+1][m+1];
for(size_t i=0;i<n;i++){
if( fgets(pattern[i],m,stdin)== NULL){
fprintf(stderr, "%s\n","Error in input" );
exit(1);
}
}
}
return 0;
}