【问题标题】:Get a large int from getchar() in C?从 C 中的 getchar() 获取大整数?
【发布时间】:2014-06-11 11:28:00
【问题描述】:

我正在读取一个带有 '$' 分隔值的文件,例如 W$65345$23425,并且一直在使用 getchar() 来获取值(而 n=getchar() != '$')等等。当我得到第二个值时,我创建一个整数列表并用 getchar() 填充该列表,所以我很确定我有一个列表 [6,5,3,4,5]。如何将其转换为值为 65345 的 int? 这是我的代码:

void read_data(char* pa,int*  pb,double*  pc){
        int n;
        pa = &n;
        n = getchar();

        int j[25];
        int m = 0;
        while ((n=getchar()) != '$'){
                j[m] = n;
                m++;
        }
        pb = &j;

        n = getchar();

        int x[25];
        m = 0;
        while ((n=getchar()) != '$'){
                x[m] = n;
                m++;
        }
        pc = &x;
        return ;
}

【问题讨论】:

  • getchar() 的返回类型是int,而不是char。你应该先解决这个问题。
  • 使用strtol将字符串转换为数字。
  • pb = &j; 抱歉,这条线让我饿了。
  • 不,请在此处使用 RTFM:man7.org/linux/man-pages/man3/strtol.3.html

标签: c input integer text-files getchar


【解决方案1】:

试试这个

int read_data()
{
    int n = getchar();
    int ret = 0;
    while(n != '$')
    {
        ret = 10 * ret + n - '0';
        n = getchar();
    }
    return ret;
}

【讨论】:

  • 多余的条件。当n >= '0' && n <= '9' 时肯定是n != '$' 所以没有必要测试'$'
【解决方案2】:

请注意,getchar 会将读取为 unsigned char 的字符转换为 int。这意味着下面的语句分配getchar读取的字符的字符代码(ASCII值) -

j[m] = n;

您可以使用标准库函数strtol 将字符串转换为long int。您必须将 int 数组更改为 char 数组。

char *endptr;  // needed by strtol

// note that the size of the array must be large enough
// to prevent buffer overflow. Also, the initializer {0}
// all elements of the array to zero - the null byte.
char j[25] = {0};

int m = 0;
while ((n = getchar()) != '$'){
    j[m] = n;
    m++;
}

// assuming the array j contains only numeric characters
// and null byte/s.
// 0 means the string will be read in base 10
int long val = strtol(j, &endptr, 0);

【讨论】:

    猜你喜欢
    • 2022-08-04
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多