添加新的阵列改变了原有的呢?

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

我试图做一个程序,询问用户名,然后重复它,说许多信件是如何在名称,该名称的第一个字母,在字母表中的名字的第一个字母是什么地方。我有这个迄今为止,但是当我推出了新的焦炭α,焦炭改为现名,即名称[0]自动变为阿尔法[0],或者一个。我该如何解决这个问题?

#include <iostream>

int main()
{
    char name[30];
    int y;

    std::cout << "What is your name? \n";    
    std::cin >> name;

    char p;
    int z=0;

    for (int i= 0; p = name[i], p != '\0'; i++)
    {
        std::cout << "Calculating... \n";
        z = i+ 1;
    }

    std::cout << "Your name is " << name << '\n';
    std::cout << "You have " << z << " letters in your name \n";
    std::cout << "The first letter of your name is " << name[0] << '\n';

    char alpha[] = "abcdefghijklmnopqrstuvwxyz";

    if (name[0] = alpha[0])
    {
        y = 1;
    }
    else
        for (y = 1 ; name[0] != alpha[y]; y++)
        {
        }

    std::cout << name[0] << " is the " <<  y << " letter of the alphabet \n";

    return 0;
}
c++
1个回答
3
投票

我的建议是使用类std::string,你可以使用它的成员一样std::string::length()以检索字符串(字符数)的长度。你也不必字母存储在字符数组,而是使用isalphatoupper ...

下面是一个例子:

std::string name;
std::cout << "name: ";
std::cin >> name;

std::cout << "Your name is: " << name << std::endl;
std::cout << "The first letter in your name is: " << name[0] << std::endl;
std::cout << "The index of the first letter in your name is: " << (int)( toupper(name[0]) - 'A' + 1 ) << std::endl;
std::cout << "There are " << name.length() << " letters in your name" << std::endl;

你可能会认为这是一个有点复杂(int)( toupper(name[0]) - 'A' + 1 )但这里是它如何工作的:

  • 用户可以输入小写或大写字母,所以我不关心,所以我将其转换为资本e.g a变得A所以从实际的信减去A加1得到其在字母索引。例如:如果用户输入hellotoupper使得hH然后H - A给出字母表字母的索引,但索引0,所以我添加1.使A是1而不是0和H是8而不是7 .. 。
© www.soinside.com 2019 - 2024. All rights reserved.