繁体   English   中英

为什么getchar()不起作用,但是getchar_unlocked()在读取字符串字符时却在主函数之外呢?

[英]Why getchar() doesn't work but getchar_unlocked() do outside main function while reading string character wise?

在这里的read()函数中,当我使用getchar()时,它仅读取一个字符。 即使while()中的条件为true,但它也会中断循环,但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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM