简体   繁体   English

尝试增加字符的ascii值时,为什么会得到随机数?

[英]Why am I getting random numbers when I try to increase the ascii value of a char?

int n = argv[i][j];
n = n + (int)argv[1]; 

/* I'm pretty sure the above part that is wrong. What I was hoping that this 
would do is take the number the person put in and increase n by that number but 
it isnt working*/ 

printf("%d\n", n);
  • i = the string numbers of the argument i =参数的字符串号
  • j = the characters of the string j =字符串的字符

What I want is to make it so when someone types ./123 12 hi I want it to increase the ascii characters of h and i by 12 or whatever number they put in. When I test my code out with 我想要做的是当有人键入./123 12 hi我希望它使hi的ASCII字符增加12或他们输入的任何数字。当我用

./123 1 hi 

I get an output of 我得到的输出

-1081510229
-1081510228

instead of 代替

105
106 

which is i and j , the next letters of h and i ij ,是hi的下一个字母

Libraries I'm using 我正在使用的图书馆

stdio.h 
studio50.h
string.h

argv[1] is a string (ie, a null-terminated char array), casting it to int doesn't give the result you expected argv[1]是一个字符串(即,以null终止的char数组),将其强制转换为int不会得到您期望的结果

You should use atoi to do the job. 您应该使用atoi来完成这项工作。 Or better, use strtol to get better stability. 或者更好,使用strtol获得更好的稳定性。

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

相关问题 为什么我的结果中会出现随机数? - Why am I getting random numbers in my result? 为什么我在这个char中得到这个十进制int? - Why I am getting this decimal int in this char? 为什么当我尝试打印字符时没有输出? - Why is there no output when I try to print a char? 为什么我会得到这些看似随机的 output? - Why am I getting these seemingly random output? 为什么在重新分配空间后将 char 分配给指向指针 char 的指针时会出现段错误? - Why am I getting a segfault when assign a char to a pointer to pointer char after realloc space for it? 为什么我在C中获得这么大的数字? - Why am I getting this huge numbers in C? 当我尝试在Linux而不是Mac上进行编译时,为什么会出现“错误:函数'fileno'的隐式声明” - Why am I getting “error: implicit declaration of function ‘fileno’” when I try to compile on Linux but not on a Mac 当我尝试释放分配的指针时,为什么会出现无效指针错误? - Why am I getting an invalid pointer error when I try to free malloced pointers? 当我尝试使用递归打印结构时,为什么会出现分段错误(核心已转储)? - Why am i getting Segmentation fault (core dumped) when i try to print a struct using recursion? 尝试将新节点添加到链接列表时,为什么会出现细分错误? - Why am I getting a Segmentation fault when I try to add a new node to my linked list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM