C程序将单词列转换为整数
C Program to convert word columns into integer
我正在用 c 编写程序来计算单词列的整数值。
#include<stdio.h>
#include<math.h>
int GetValue(char ch){
int c=ch;
if(ch>='a'&&ch<='z'){
return abs(96-c);
}
if(ch>='A'&&ch<='Z'){
return abs(64-c);
}
return -1;
}
void main()
{
char col[10];
char *str;
int len,sum=0,temp=0,i;
printf("Enter the column string : ");
scanf("%s",&col);
len = strlen(col);
memcpy(str,col,len);
str[len]='[=10=]';
printf("Entered characters are %s and its length is %i",col,len);
for(i=0;i<len;i++){
sum+=GetValue(str[i])*(pow(26,len-1-(temp++)));
}
printf("Value of column is %d",sum);
}
当我编译它时它给出了 3 个警告
columnno.c:20:2:警告:格式“%s”需要类型为“char ”的参数,但参数 2 的类型为“char ()[ 10]' [-W格式=]
scanf("%s",&col);
^
columnno.c:21:8: 警告:内置函数“strlen”的隐式声明不兼容[默认启用]
len = strlen(列);
^
columnno.c:22:2:警告:内置函数“memcpy”的隐式声明不兼容[默认启用]
memcpy(str,col,len);
^
输出
输入列字符串:abc
分段错误(核心已转储)
请帮忙!!!
1。
无需使用 %s
.
将数组地址传递给 scanf()
scanf("%s",&col);
改为
scanf("%s",col);
2。
在执行 memcpy(str,col,len);
之前,您应该将内存分配给 str
作为其 char *
。否则,您正在访问 str
中的随机值作为内存位置,导致未定义的行为 - 很可能是分段错误。
最好使用 strdup()
。
改变
memcpy(str,col,len);
str[len]='[=12=]';
到
str = strdup(col);
但是,请确保您输入的字符串不超过 9 个字符,以便其正确存储在 cols
。
添加到上述答案中。包含 strlen()
的库头文件
#include<string.h>
包含函数的定义strlen()
您收到这些警告是因为您正在尝试使用以前未声明的函数。
要解决这个问题,你必须在使用函数之前声明它们;通常你通过包含适当的 header 来做到这一点。
尝试 #include <string.h>
这就是定义 strcpy
和 strncpy
的地方。
你的代码会出现运行时错误,因为你在 str
中存储了一些东西,但没有为其分配任何内存。
我正在用 c 编写程序来计算单词列的整数值。
#include<stdio.h>
#include<math.h>
int GetValue(char ch){
int c=ch;
if(ch>='a'&&ch<='z'){
return abs(96-c);
}
if(ch>='A'&&ch<='Z'){
return abs(64-c);
}
return -1;
}
void main()
{
char col[10];
char *str;
int len,sum=0,temp=0,i;
printf("Enter the column string : ");
scanf("%s",&col);
len = strlen(col);
memcpy(str,col,len);
str[len]='[=10=]';
printf("Entered characters are %s and its length is %i",col,len);
for(i=0;i<len;i++){
sum+=GetValue(str[i])*(pow(26,len-1-(temp++)));
}
printf("Value of column is %d",sum);
}
当我编译它时它给出了 3 个警告
columnno.c:20:2:警告:格式“%s”需要类型为“char ”的参数,但参数 2 的类型为“char ()[ 10]' [-W格式=] scanf("%s",&col); ^
columnno.c:21:8: 警告:内置函数“strlen”的隐式声明不兼容[默认启用] len = strlen(列); ^
columnno.c:22:2:警告:内置函数“memcpy”的隐式声明不兼容[默认启用] memcpy(str,col,len); ^
输出
输入列字符串:abc
分段错误(核心已转储)
请帮忙!!!
1。
无需使用 %s
.
scanf()
scanf("%s",&col);
改为
scanf("%s",col);
2。
在执行 memcpy(str,col,len);
之前,您应该将内存分配给 str
作为其 char *
。否则,您正在访问 str
中的随机值作为内存位置,导致未定义的行为 - 很可能是分段错误。
最好使用 strdup()
。
改变
memcpy(str,col,len);
str[len]='[=12=]';
到
str = strdup(col);
但是,请确保您输入的字符串不超过 9 个字符,以便其正确存储在 cols
。
添加到上述答案中。包含 strlen()
#include<string.h>
包含函数的定义strlen()
您收到这些警告是因为您正在尝试使用以前未声明的函数。
要解决这个问题,你必须在使用函数之前声明它们;通常你通过包含适当的 header 来做到这一点。
尝试 #include <string.h>
这就是定义 strcpy
和 strncpy
的地方。
你的代码会出现运行时错误,因为你在 str
中存储了一些东西,但没有为其分配任何内存。