在 read() 函数中,当我使用 getchar() 时,它只读取一个字符。即使 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...9 和 '+' 和 '-' 以外的字符
- 正确检查 I/O 错误
- 格式易于阅读和理解
- 记录为什么包含每个头文件
- 使用与 C 库名称不冲突的函数名称
- 正确终止格式字符串到
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;
}
关于c - 为什么 getchar() 不起作用,但 getchar_unlocked() 在读取字符串字符时在 main 函数之外执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46406187/