c - 为什么 getchar() 不起作用,但 getchar_unlocked() 在读取字符串字符时在 main 函数之外执行?

标签 c string getchar

在 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;
}

最佳答案

以下建议代码:

  1. 干净地编译
  2. 执行所需的功能
  3. 正确处理 0...9 和 '+' 和 '-' 以外的字符
  4. 正确检查 I/O 错误
  5. 格式易于阅读和理解
  6. 记录为什么包含每个头文件
  7. 使用与 C 库名称不冲突的函数名称
  8. 正确终止格式字符串到 printf(),以便数据立即显示在终端上。
  9. 如果输入没有包含足够的行来匹配第一行的数字,仍然包含一个潜在的问题。

现在建议的代码:

#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/

相关文章:

c - realloc 如何处理使用 calloc 分配的内存?

c++ - iphone 的贝叶斯网络库?

c - 如何在 Codesys v3 中创建指向函数的指针

c++ - getchar()有什么用?

c - 为什么 getchar() 的行为不同?

c - 在 PKCS#12 结构中管理多个 RSA key /证书

python - 将字符串转换为浮点型(在字符串内进行计算)

c# - String.Trim() 删除的内容超出需要?

objective-c - 如何从 Objective-C 中的 NSString 中获取前 N 个单词?

对 getchar() 循环的内部工作方式感到困惑