1
#include <stdio.h>
#define MAX_SIZE 20

int main()
{
  int age;
  char name[MAX_SIZE];
  float wage;

  printf("input name, age and wage: ");

  scanf("%s %s %s", name, &age, &wage); //LINE 10
}

尝试编译后:

lab4q5.c: In function 'main':
lab4q5.c:10: warning: format '%s' expects type 'char *', but argument 3 has type 'int*'
lab4q5.c:10: warning: format '%s' expects type 'char *', but argument 4 has type 'float *'
lab4q5.c:16: warning: control reaches end of non-void function

我是 C 编程新手,想扫描一个floatandint但作为我的一个实验室的字符串。我知道我可以更改%s %sto%f %d并且它应该可以正常编译,但是我被要求扫描是否为%s,任何帮助将不胜感激:我遇到问题的部分问题如下:

使用循环读取输入(来自标准输入),每行一个输入,关于名称年龄工资形式的用户信息,其中年龄是整数文字,工资是浮点文字,最多 2 个十进制数。• 使用scanf(“%s %s %s”, 姓名, 年龄, 工资) 读入三个输入“字符串”;

因此,在阅读了评论后,我决定将它们格式化为字符串,然后担心稍后将它们操作为 int 和 float,这就是我目前所拥有的:

#include <stdio.h>
#define MAX_SIZE 20
#define MAX_AGE 3
int isXX(char name[])
{
if (name[0] == 'X' && name[1] == 'X' && name[2] == '\0')
return 0; //return return false to quit
else 
return 1; //return true 
}

int main()
{

char age[MAX_AGE];
char wage[MAX_SIZE];
char name[MAX_SIZE];

printf("input name, age and wage: ");//enter name as XX to quit
scanf("%s %s %s", name, age, wage);
    while(isXX(name[])) // //LINE 22
    {
        printf("input name, age and wage: ");//enter name as XX to quit 
        scanf("%s %s %s", name, age, wage);
    }
return 0;
}

现在我不确定为什么我在编译器中遇到这个错误,但我是

lab4q5.c: In function âmainâ:
lab4q5.c:22: error: expected expression before â]â token
4

3 回答 3

5

Use atoi and atof functions to convert from string to int and float respectively. You can first read age and wage as strings and use those functions to convert from string to the respective types and assign them to corresponding new variables.

By the way do not forget to include stdlib.h in order it be working properly.

Corrected Version of your code:

#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 20

int main()
{
char age[MAX_SIZE];
char name[MAX_SIZE];
char wage[MAX_SIZE];
int ageInteger;
float wageFloat;
printf("input name, age and wage: ");
scanf("%s %s %s", name, age, wage); //LINE 10

ageInteger=atoi(age);
wageFloat=atof(wage);
printf("Age:%d, Wage:%f\n",ageInteger,wageFloat);

return 0;
}

Hope this helps...

EDIT:

One comment points out that atoi, atof has undefined behaviour in erroneous cases and also suggests to use stdtol and stdtod instead of atoi, atof. I myself don't know about this. So, take this as a caution before using them and chose carefully chose what you want to do by some research.

于 2013-06-12T15:15:36.297 回答
3

您正在将它们作为字符串读取并将它们分配给非字符串变量。

因此,您要么需要将代码更改为:

 int age;
 char name[MAX_SIZE];
 float wage;

至:

 char age [3];
 char name[MAX_SIZE];
 char wage[MAX_SIZE];

或者

scanf("%s %s %s", name, &age, &wage)

scanf("%s %d %f", name, &age, &wage)

根据对您问题的评论,我的问题是您为什么希望它们作为字符串开头?

于 2013-06-12T15:08:10.523 回答
2

您正在尝试读取字符串,但将值分配给非字符串。

尝试在 scanf 格式字符串中使用正确的类型:

scanf("%s %d %f", name &age &wage);

您可以查看如何在 wikipedia上使用 scanf 格式字符串

于 2013-06-12T15:10:10.580 回答