当我使用 getchar()时,read()函数中只读取一个字符。即使 while()中的条件为真,但 getchar_unlocked()读取字符直到给定条件失败,它也会中断循环 代码是计算最大值,如:
input :
4
8-6+2+4+3-6+1
1+1+1+1
2+3+6+8-9
2+7+1-6
output :
10 //(which is max value of 3rd string)
代码:
#include <stdio.h>
inline int read(int *value) {
char c, c1 = '+';
*value = 0;
c = getchar_unlocked();
while ((c >= '0' && c <= '9') || c == '+' || c == '-') {
if (c == '+' || c == '-') c1 = c;
else *value = (c1=='+' ? *value + (c-'0') : *value - (c-'0'));
c = getchar_unlocked();
}
return *value;
}
int main()
{
int n, max=0, val;
scanf("%d", &n);
char x = getchar();
while(n--) {
read(&val);
max = val>max?val:max;
}
printf("%d", max);
return 0;
}
答案 0 :(得分:0)
以下提议的代码:
printf()
,以便数据立即显示在终端上。现在建议的代码:
#include <stdio.h> // scanf(), getchar()
#include <limits.h> // INT_MIN
#include <ctype.h> // isdigit()
#include <stdlib.h> // exit(), EXIT_FAILURE
inline int myRead( void )
{
int c;
char c1 = '+';
int value = 0;
while( (c = getchar()) != EOF && '\n' != c )
{
if (c == '+' || c == '-')
c1 = (char)c;
else if( isdigit( c ) )
value = (c1=='+' ? value + (c-'0') : value - (c-'0'));
}
return value;
}
int main( void )
{
int n;
int max = INT_MIN;
int val;
if( 1 != scanf("%d", &n) )
{
fprintf( stderr, "scanf for number of following lines failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
while(n--)
{
val = myRead();
max = val>max?val:max;
}
printf("%d\n", max);
return 0;
}