[英]sscanf casting warning c
該程序的目的是獲取一個包含數字和空格的字符串作為輸入,然后用 strtok 拆分字符串並將每個數字插入數組中。 最后,我從數組中將數字發送到 function checkPowerOfTwo,它確定數字是否是 2 的冪並打印一個帶有計算的字符串。
警告說: passing argument 1 of 'sscanf' makes pointer from integer without a cast [-Wint-conversion]|
警告發生在包含 sscanf 的兩行上。 關於如何解決這些警告的任何想法? 我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int checkPowerOfTwo(int x);
int main()
{
int exp,size,*numbers,sum=0;
char term,*str=NULL,*token;
printf("Enter size of input:");
if(scanf("%d%c", &size, &term) != 2 || term != '\n'){
printf("Invalid Size\n");
return 0;
} if(size<=0){
printf("Invalid size\n");
return 0;
} else{
numbers=(int*)malloc(size * sizeof(int));
str=(char*)malloc(sizeof(int)*(size+1) + (size-1)*sizeof(char));
if(numbers==NULL||str==NULL){
printf("Out of memory\n");
return 0;
} //else{
//printf("Memory allocated\n");
//}
printf("Enter numbers:");
fgets (str, sizeof(int)*(size+1) + (size-1), stdin);
//printf("%s",str);
token=strtok(str," ");
while(token!=NULL){
for(int i=0;i<size;i++){
//printf("%s\n",token);
numbers[i]=(int)token;
token=strtok(NULL," ");
}
}
}
for(int j =0;j<size;j++)
{
exp=checkPowerOfTwo(numbers[j]);
if (exp>=0){
int x;
sscanf((int)numbers[j],"%d",&x);
printf("The number %d is a power of 2: %d=2^%d\n",x,x,exp);
sum+=exp;
}
}
printf("Total exponent sum is %d",sum);
free(numbers);
free(str);
}
int checkPowerOfTwo(int n)
{
int x;
int exponent=0;
sscanf((int)n,"%d",&x);
//printf("checking number %d\n",x);
if (x==0){
return -1;
} if (x==1){
return 0;
}
while( x != 1)
{
if(x % 2 != 0){
return -1;
}
x /= 2;
exponent++;
}
return exponent;
}
我嘗試在兩個 sscanf 行中使用轉換為 (int) 但警告仍然存在。
這是一個從字符串中提取未知數量的整數的示例。
它不使用strtok
,而是通過將緩沖區指針推進到成功掃描的每個項目來工作。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main (void)
{
char input[256];
puts("Enter some numbers on one line:");
if(fgets(input, sizeof input, stdin) == NULL) {
puts("Error in input");
exit(1);
}
int num;
int len;
char *buf = input;
puts("The numbers are:");
while(sscanf(buf, "%d%n", &num, &len) == 1) {
if(!isspace(buf[len])) {
puts("Error in input");
exit(1);
}
printf("num=%d\n", num);
buf += len;
}
}
節目環節:
Enter some numbers on one line: 123 456 789 The numbers are: num=123 num=456 num=789 Enter some numbers on one line: 123a 456 The numbers are: Error in input
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.