gpt4 book ai didi

将返回的 char 转换为 int

转载 作者:太空宇宙 更新时间:2023-11-04 07:23:15 24 4
gpt4 key购买 nike

我是第一次尝试使用 C。我有一个调用 bash 脚本的程序。此脚本 printf 的数字通过

COUNT=$(ls | grep tool | wc -l)
printf "%s" "$COUNT"

我想获取这个数字并对其执行简单的数学运算。但是,我似乎无法将此值转换为 int 以便除以 2。

我试过类似 https://stackoverflow.com/a/868508/183254 的东西

int myint = otherint - '0';

当我对其进行编译并尝试进行数学计算时会产生段错误。

我也试过很多次

int cc;
cc = count - '0';
// warning: assignment makes integer from pointer without a cast [enabled by default]
// or
// warning: initialization from incompatible pointer type [enabled by default]

没有用。

我已经阅读了几篇关于谷歌搜索这些错误的帖子,但似乎仍然无法理解正在发生的事情,我想也许是因为我没有上下文提问者想要达到的目的。

这是我放在一起的一个小演示,试图了解发生了什么。结果这让我更加困惑。

int main(){
char *x;
x="44";
int xx;
xx = (int) x - '0';
printf("x is : %s\n", x);
printf("xx is : %d\n",xx);// x is : 23703288
char command[64];

char path[9];// won't work if set to <=8
int status;
FILE *fp;

//this shell script just counts the number of files in a directory
//that match a certain string.
strcpy(command, "/test/test.sh");// returns 0-9; in this case it's returning 4 (supposed to anyway)


fp = popen(command, "r");
if (fp == NULL)
/* Handle error */;

while (fgets(path, 9, fp) != NULL) //again, won't work if arg2 is <=8
//printf("%s", path);

status = pclose(fp);

int cc;
cc = (int) path - '0';

printf("result of path is %s\n",path ); // result of path is 4
printf("result of conversion is %d\n", cc);// result of conversion is 1582717056
}

output:

x is : 44
xx is : 182607602
result of path is 4
result of conversion is 1423813191

我已经找到并阅读了几本入门书,但我不知道它们是旧的还是什么,但除了稍微解释一下指针之外没有太大帮助。

真正让我感到困惑的是上面代码片段中发生的事情:

x is : 44

好的,这是有道理的,因为我输入了 x="44";

xx is : 182607602

哇。这看起来一定是指向某个地址的指针。根据我读过的入门书,这应该来自 &x;; 这样的东西。为什么它来自应该将 char 44 转换为 int 44 的内容?

result of path is        4

好的(除了所有那些空格)。它几乎看起来像是被填充或什么的。 char path[9];while (fgets(path, 9, fp) != NULL) 加深了我的怀疑,但正如所评论的那样 <= 8 不起作用。

result of conversion is 1423813191

相同;似乎指向地址空间。不明白为什么。

对于许多来自其他语言的人(包括我)来说,这似乎是一个困惑点——这是我的借口,我会坚持下去。

任何指针将不胜感激(好的入门书,这段代码中发生了什么,任何真的)。

谢谢。


在 youtube 上找到了一个由 9 部分组成的优秀系列,它很好地解释了一些 C 基础知识: https://www.youtube.com/playlist?list=PLkB3phqR3X40reMCBYSoNUPbDvM4kybMs .第 7 部分特别有用——它涵盖了指针,这是我困惑的一个重要部分。

最佳答案

 char *x;
x="44";
int xx;
xx = (int) x - '0';

在这里,您通过将 指针 转换为 int 来减去 '0'。如果 xchar 类型,则此逻辑将起作用。

您真正想要的是将字符串转换为 using strtol() 或相关函数。

以同样的方式,您也可以将 path 转换为整数,稍后在您的代码中执行此操作。

关于将返回的 char 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20107216/

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