顺便说一下,我使用 CLion。
int ch;
printf("Insert the operation you want to execute: ");
scanf("%d", &ch); //HERE
Run Code Online (Sandbox Code Playgroud)
我将 ch 声明为一个整数变量,并使用scanf和%d并且我希望用户插入一个值以插入到 ch 变量中,但是这里会弹出一个警告并说:“‘scanf’用于将字符串转换为整数值”
我不明白为什么...
这是完整的代码,如评论中所要求:(代码被修改,因为我从昨天开始更改了它)
typedef unsigned int boolean;
struct list{
float * buffer;
int size;
int head;
int tail;
};
int getsize();
float getvalue();
void init(struct list*, int);
boolean suf_insert(struct list*, float, int);
boolean pre_insert(struct list*, float, int);
void visit(struct list*);
int main(){
struct list listA;
struct list listB;
int size=0;
int ch;
while(1){
printf("Sequential Lists operations\n");
printf("1. Insert the size of the array\n");
printf("2. Initialize the list A\n");
printf("3. Initialize the list B\n");
printf("4. \n");
printf("5. \n");
printf("6. \n");
printf("7. \n");
printf("\nInsert the operation you want to execute: ");
scanf("%d", &ch);
switch(ch){
case 1: size=getsize();
break;
case 2: init(&listA, size);
break;
case 3: init(&listB, size);
break;
case 4: getvalue();
break;
case 5:
break;
case 6:
break;
case 7:
break;
default: printf("\nInvalid command. Retry\n");
break;
}
}
}
int getsize(){
int size;
printf("Insert the size of the list you want to create: ");
scanf("%d", &size);
return size;
}
float getvalue(){
float value;
printf("The value you want to insert: ");
scanf("%f", &value);
return value;
}
void init(struct list * ptr, int size) {
if (size != 0) {
ptr->buffer = (float *) malloc(size * sizeof(int));
ptr->size = size;
ptr->head = 0;
ptr->tail = 0;
} else {
printf("\nBefore continue, insert the size.\n");
}
}
boolean suf_insert(struct list * ptr, float value, int size){
if(((ptr->tail + 1) % ptr->size) != ptr->head && size!=0) {
ptr->buffer[ptr->tail] = value;
ptr->tail = (ptr->tail + 1) % ptr->size;
return TRUE;
} else {
return FALSE;
}
}
boolean pre_insert(struct list * ptr, float value, int size){
if(((ptr->tail + 1) % ptr->size) != ptr->head && size!=0){
ptr->head = (ptr->head + ptr->size - 1) % ptr->size;
ptr->buffer[ptr->head] = value;
return TRUE;
}else{
return FALSE;
}
}
void visit(struct list * ptr){
int position;
for(position=ptr->head; position!=ptr->tail; position=(position+1)%ptr- >size){
printf("%f", ptr->buffer[position]);
}
}
Run Code Online (Sandbox Code Playgroud)
似乎我必须重复:这段代码并不完美,也许恰恰相反!我还在努力!
警告清楚地说明了原因;您省略了“函数不会报告转换错误”的部分。然而,这显然也是无稽之谈:strtol()也不报告转换错误——如果有转换错误,它只会返回零——但这与成功转换“0”没有区别。
随着scanf()至少该返回值是成功与否的明确指示。这是事实,scanf()不报告转换错误,它会报告成功转换的计数,所以当只有一个转换在这种情况下,返回值为零恰好报告转换错误。
“警告”是由您的 IDE 生成的,而不是您的编译器,只是建议(IMO 的错误建议)-您可以明确选择忽略该建议。
但你至少应该检查从返回值scanf()。如果scanf()失败,则 的值ch未定义。的一个优点strtol()是失败时它至少返回一个定义的值 - 零 -至少在这种特定情况下,零是一个无效值,因此它具有优点;但不是因为警告中建议的原因。
| 归档时间: |
|
| 查看次数: |
771 次 |
| 最近记录: |