作为一项学习练习,我正在创建一个程序,将通过argv[1]
输入的字符转换为整数。然后程序找到整数的数字均值。
例如:abc
为123
,1+2+3 = 6
,六为数字均值。该程序的第一部分有效,但我无法正确编码找到数字均值的部分。
word abc
的输出应为123 6
;相反,它是123 150
。
编辑:已解决!
#include <stdio.h>
#include <strings.h>
int main(int argc, char *argv[])
{
char stra[27], strb[0];
int str_num, str_len;
int final = 0;
if (argv[1][0] < 'a')
{
printf("!Argument missing!");
return 0;
}
strcpy(stra, argv[1]);
str_len = strlen(stra);
for (str_num = 0; str_num < str_len; str_num++)
{
if (stra[str_num] <= 'z' && stra[str_num] >= 'a')
{
strb[str_num] = (stra[str_num] - 'a' + 1) % 9 + '0';
if (strb[str_num] == '0')
{
strb[str_num] = '9';
}
}
else
{
printf("%s !Please use only the lower case!", stra);
return 0;
}
}
for (str_num = 0; str_num < str_len; str_num++)
{
final += strb[str_num] - '0';
}
printf("%s %i", strb, final);
return 0;
}
答案 0 :(得分:0)
在第一次检查时,如果这是
,您的程序似乎或多或少会起作用strb[str_num] = (stra[str_num] - 'a') % 9 + 1
此外,strb
也需要27个字符,而不是0; 0元素数组在保存非零数据量方面相当差!
您需要使用argc
检查参数 - 即
if (argc != 2)
// complain here
最后,当您打印结果时,需要将序号转回字符。将strb
打印为char*
不会给您123
,而是^A^B^C
,而不是您想要的。因此,您需要在循环中打印这些字符,通过将'0'
的偏移量添加回来调整每个字符。
答案 1 :(得分:0)
好像你已经跑过缓冲区的末尾strb
:
char strb[0];
答案 2 :(得分:0)
strb[str_num] = (stra[str_num] - 'a') % 9 - 207;
207
是这里最大的问题(除了你的一个一个错误)。这一行应为:
strb[str_num] = (stra[str_num] - 'a' + 1) % 9;
答案 3 :(得分:0)
#include <stdio.h>
#include <strings.h>
int main(int argc, char *argv[])
{
char *stra;
char *strb;
int str_num;
int str_len;
int final;
final = 0;
if ( (argc >= 2 && argv[1][0] < 'a') || (argc <= 1))
{
printf("!Argument missing!");
return 0;
}
str_len = strlen(argv[1]);
strb = (char*) malloc((str_len+1)*sizeof(char));
for (str_num = 0; str_num < str_len; str_num++)
{
if (argv[1][str_num] <= 'z' && argv[1][str_num] >= 'a')
{
strb[str_num] = (argv[1][str_num] - 'a'+1) % 9 + '0'; //to get string with numbers from 1 to 9
}
else
{
printf("%s !Please use only the lower case!",argv[1]);
return 0;
}
}
strb[str_len] = '\0' // put the end char of the string : mandatory to print it.
for (str_num = 0; str_num < str_len; str_num++)
{
final += strb[str_num] - '0'; // count the sum of the numbers from 1 to 9 ?
}
printf("%s %i",strb,final);
free(strb);
return 0;
}