如何从数组中获取特定字符,以便可以放入另一个数组中

问题描述 投票:-1回答:1

im是C ++的新手基本上,我被要求编写一个程序,要求输入名字的首字母,中间名的缩写和整个姓氏,并在一行上输出名字的首字母,在另一行上输出名字的中间名,在另一行上输出姓氏。我一开始只是做一个程序,但是输入并没有全部输入,而且我不确定该怎么做,如果我的解释不是很有帮助,对不起。

我被要求做的事情编写程序以提示用户在单行中输入其名字的首字母,然后输入一个空格,其中间名的首字母,后跟一个空格以及整个姓氏。将此存储在char数组中。然后,程序应在一行上输出第一个首字母,然后在单独的一行上输出中间的首字母,并在自己的一行上输出姓。该程序旨在演示char数组的用法。确保使用char数组完成此程序,并且用户输入的数据存储在单个char数组中。之后,您可以将名称的各个部分分成单独的数组,但是从控制台进行的初始读取应将整个输入放入单个char数组中。

#include <iostream>
using namespace std;

int main()
{
    char firstNameInitial[2];
    char middleNameInitial[2];
    char surname[11];

cout << "Enter your first name initial: ";
cin >> firstNameInitial;
cout << "Enter your middle name initial: ";
cin >> middleNameInitial;
cout << "Enter your surname initial: ";
cin >> surname;

cout << firstNameInitial << endl << middleNameInitial << endl << surname << endl;

system("pause");
return 0;
}

这是我起初所做的,但是输入在不同的行上,我将如何在1中执行此操作,而输出却在不同的位置

c++ arrays char
1个回答
0
投票
如何从数组中获取特定的字符,以便将其放入另一个数组?

这是初学者如何学习数组的方法。全面了解数组的基础知识和索引的用法以访问数组元素,从而解决您的问题。您可以参考this教程。

解决方案

您可以通过多种方式解决您的任务。我将向您展示使用fgets功能的解决方案。此外,您不需要任何其他变量即可分隔输入。如果您现在已经掌握数组操作的基本知识,则可以只使用一个数组来执行读取和显示操作。

#include <iostream> // Modify this according to your requirements #define NAME_SIZE 30 int main() { // A single character array as per the constraints char name[NAME_SIZE]; // Do it in the C-style! fgets(name, NAME_SIZE, stdin); // First initial std::cout << name[0] << '\n'; // name[1] is the space that follows // Second initial std::cout << name[2] << '\n'; // name[3] is the space that follows // Display the surname which starts at index 4 // Remember that the string terminates with a null character for (unsigned i = 4; name[i] != '\0'; ++i) std::cout << name[i]; // Success return 0; }

© www.soinside.com 2019 - 2024. All rights reserved.