gpt4 book ai didi

c - C中的Read()整数

转载 作者:行者123 更新时间:2023-11-30 20:59:25 25 4
gpt4 key购买 nike

我尝试了下面的代码,但结果不正确。我认为缓冲区大小的东西可能会以错误的方式实现。

int f(int* as) {
*as = read(STDIN_FILENO, as, sizeof(int));
} //i print 123

int s;
f(&s);

printf("%d",s); // prints 4

最佳答案

有两件事会阻止程序给出您期望的结果

1) 使用 read 从标准输入(字符)读取并将其存储到(二进制)整数

2) 将read的结果存储到同一个整数中,覆盖1)中存储的(错误)值

看看 scanffgets (atoi...),读入字符数组(字符串),然后将读取到的字符转换为二进制数,例如

char str[20];
fgets(str, 20, stdin);
int s = atoi(str);

阅读版本

char str[20];
ssize_t nread = read(STDIN_FILENO, str, 20);
int s = atoi(str);

参见what an integer is ,

关于c - C中的Read()整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47542729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com