[英]Creating an array with char in C, taking two words from the user, changing the places of the words and giving them all to the screen at the end
预期结果:
4
安雅·泰勒
比尔坎普
丹尼斯刘易斯
摩西·英格拉姆
泰勒·安雅
比尔营
刘易斯·丹尼斯
英格拉姆·摩西
我已经尝试了很多东西。 虽然网上也有人遇到过类似的问题,但我没有遇到过这样的例子。
注意:我正在寻找除特殊库和数组函数之外的解决方案,它们使它变得容易。 我想到了类似 while (array [i]! = '\\ 0') 的东西。 我想创建一个新数组,将其保存在那里并打印出来。 但我的想法失败了。
#include<stdio.h>
int main(void)
{
int nbnames=0,i=0;
char Fname[101];
char Lname[101];
scanf("%d",&nbnames);
for(i=0;i<nbnames;i++)
{
scanf("%s %s",Fname,Lname);
printf("%s %s\n",Lname,Fname);
}
return 0;
}
这应该是非常微不足道的。 为方便起见,您可以使用struct
来存储每个人的名字和姓氏 -
typedef struct Person
{
char first_name[101];
char last_name[101];
} Person;
现在,您所要做的就是分配一个大小为nbnames
(由用户提供)的Person
结构数组 - 然后像您一样扫描名字和姓氏,并将它们存储在每个Person
结构中大批。
所以完整的程序看起来像-
#include <stdio.h>
#include <stdlib.h>
typedef struct Person
{
char first_name[101];
char last_name[101];
} Person;
int main(void)
{
Person* persons = NULL;
size_t nbnames;
/* Get the number of persons to be entered */
if (scanf("%u", &nbnames) != 1)
{
/* scanf could not parse input - probably not an unsigned integer */
fprintf(stderr, "Invalid input\n");
return 1;
}
/* Allocate enough memory for the array of persons */
persons = malloc(nbnames * sizeof(*persons));
if (!persons)
{
/* Failed allocating memory */
fprintf(stderr, "Could not allocate memory for persons array\n");
return 1;
}
/* Take the inputs */
for (size_t i = 0; i < nbnames; i++)
{
scanf("%100s %100s", persons[i].first_name, persons[i].last_name);
}
/* Print the outputs */
for (size_t i = 0; i < nbnames; i++)
{
printf("%s %s\n", persons[i].last_name, persons[i].first_name);
}
/* Free the persons array */
free(persons);
return 0;
}
4
安雅·泰勒
比尔坎普
丹尼斯刘易斯
摩西·英格拉姆
泰勒·安雅
比尔营
刘易斯·丹尼斯
英格拉姆·摩西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.