当我尝试增加char的ascii值时,为什么我会得到随机数?

时间:2014-05-15 00:39:47

标签: c string ascii

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 =参数的字符串编号
  • j =字符串的字符

我想要的是当有人输入./123 12 hi时,我希望它能将hi的ascii字符增加12或者放入任何数字。当我输入时用

测试我的代码
./123 1 hi 

我得到

的输出
-1081510229
-1081510228

而不是

105
106 

ijhi的下一个字母

图书馆我正在使用

stdio.h 
studio50.h
string.h

1 个答案:

答案 0 :(得分:6)

argv[1]是一个字符串(即一个以null结尾的char数组),将其强制转换为int并不能给出预期的结果

您应该使用atoi来完成这项工作。或者更好的是,使用strtol来获得更好的稳定性。