arrays - 在 C 中使用 char 创建一个数组,从用户那里获取两个单词,更改单词的位置并在最后将它们全部显示在屏幕上
问题描述
预期结果:
输入:
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;
}
解决方案
这应该是微不足道的。为方便起见,您可以使用 astruct
来存储每个人的名字和姓氏——
typedef struct Person
{
char first_name[101];
char last_name[101];
} Person;
现在,您所要做的就是分配一个Person
结构数组,其大小nbnames
(由用户提供) - 然后简单地扫描您已经存在的名字和姓氏并将它们存储在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
安雅·泰勒
比尔·坎普
丹尼斯·刘易斯
摩西英格拉姆
泰勒安雅
比尔营
刘易斯丹尼斯
英格拉姆·摩西
推荐阅读
- python - Tkinter PhotoImage 不存在
- python - 自动生成访问令牌
- c# - ASP.NET Core 3.0 WebAPI - 为什么在控制器方法中处理异常时仍会收到 InternalServerError?
- javascript - 如何将 Laravel 路由注入到打包在 webpack 中的 js 文件中?
- interceptor - JEE:如何拦截@PostCostruct 方法?
- image - 无法从嵌套的 vue 组件加载图像
- c# - 在 C# 中获取变量名
- http - 服务器端的代码执行流程(golang)
- sql - 添加缺少的每月行
- android - 如何在android中每小时旋转三次