Use scanf to read in character strings, single characters and numbers (the most frequently occurring character strings are counted)

//Use scanf to read in the difference between character strings, single characters, and numbers
//The dimension reduction of two-digit arrays is very convenient

#include<stdio.h>
#include<string.h>
void main(){
    
    
	int n;
	while(~scanf("%d",&n)&&n){
    
    //会在缓冲区留下一个换行符
	//	getchar();不需要它的原因③
		char b[1005][20];
		int max=0,maxi,i,j,count;
		for(i=0;i<n;i++){
    
    
			scanf("%s",b[i]);//即使前面没有getchar,由于类型是字符串,不会读取前面的getchar,下面一个同理
		//	getchar();不需要它的原因③
		}
		for(i=0;i<n;i++){
    
    
			count=0;
			for(j=0;j<n;j++)
				if(strcmp(b[i],b[j])==0) count++;
			if(count>max) {
    
    max=count;maxi=i;}
		}
		printf("%s\n",b[maxi]);
	}
}

Summary
//Use scanf("%c",&c) to read c (c is a char type). If there is a newline character or space before reading, then c will read the newline character or space of the previous buffer, The solution is to getchar() first;
//If you use scanf("%s",str) to read str(char str[] or char str[][]), even if the buffer has a newline character or Spaces will not be read;
//Other numeric types have no such problems.

#include<stdio.h>
#include<string.h>
void main(){
    
    
	int repeat;
	scanf("%d",&repeat);
	getchar();//用getchar()的原因①
	while(repeat--){
    
    
		char s[1000],c;
		gets(s);
		//不用加getchar()的原因②
		scanf("%c",&c);
		getchar();//用getchar()的原因①
		printf("result: ");
		for(int i=0;i<strlen(s);i++){
    
    
			if(s[i]==c) continue;
			else printf("%c",s[i]);
		}
		printf("\n");
	}
}

Summary
// Before receiving: ③scanf("%s",s) receives the string and automatically discards the carriage return in the buffer,
①but gets(s) will receive the carriage return in the buffer; //After receiving: ②gets(s) The carriage return used to end the input will be discarded, and scanf("%s",s) will leave a carriage return in the buffer;

//scanf ends an input with space, enter, and tab, and will not discard the last terminator (left in the buffer);
//getchar ends the input with enter, and will not discard the last terminator (left in the buffer);
/ /gets End input with enter, enter will be discarded.

Guess you like

Origin blog.csdn.net/cwindyc/article/details/107007559