我在使用此代码时遇到麻烦。
基本上,我必须使用动态字符串创建一个结构,然后要求用户为每个字符串分配内存。之后,询问用户他的名字,姓氏和城市,使用strupr()将所有字符串转换为mayus,最后进行打印。
/*16.ask user his name,surname and city. Then,convert all to MAYUS(with strupr()), and print all data(use a structure and dynamic memory).*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct data{
char *name;
char *surname;
char *city;
}user;
void flush_in();
int main(){
int n1,n2,n3;
printf("type memory for name: ");
scanf("%i",&n1);
user.name=malloc(sizeof(int)*n1);
printf("type memory for surname: ");
scanf("%i",&n2);
user.surname=malloc(sizeof(int)*n2);
printf("type memory for city: ");
scanf("%i",&n3);
user.city=malloc(sizeof(int)*n3);
flush_in();
printf("type name: ");
scanf("% [^\n]",&user.name);
flush_in();
printf("type surname: ");
scanf("% [^\n]",&user.surname);
flush_in();
printf("type city: ");
scanf("% [^\n]",&user.city);
strupr(user.name);
strupr(user.surname);
strupr(user.city);
printf("\nname: %s",user.name);
printf("\nsurname: %s",user.surname);
printf("\ncity: %s",user.city);
return 0;
}
void flush_in(){
int ch;
while((ch=fgetc(stdin))!=EOF && ch!='\n'){}
}
一切正常,直到输出,它返回:
name: : P¡
surname: P¡
city: P¡
为什么会这样?可以返回我的名字,姓氏和城市,但我不知道出了什么问题。