如何大写第一个字母

时间:2014-10-26 19:06:39

标签: c++

我怎样才能编写一个读取你的名字和姓氏的C程序,然后将它们转换为大写和小写字母......我知道上下字母如何但dk如何为名字和姓氏做什么sugegstion?...

#include<iostream>
#include<string.h>
using namespace std;
int i;
char s[255];

int main()
{
    cin.get(s,255,'\n');
    int l=strlen(s);
    for(i=0;i<l;i++)
......................................


cout<<s; cin.get();
    cin.get();
    return 0;
}

2 个答案:

答案 0 :(得分:1)

您可以直接在std::string&#39}中读取名字和姓氏。没有理由自己管理缓冲区或猜测它们应该或应该是什么尺寸。这可以用这样的东西来完成

std::string first, last;

//  Read in the first and last name.
std::cin >> first >> last;

您需要根据需要将字符串转换为大写/小写字母。这可以使用C ++标准库中提供的std::toupperstd::tolower来完成。只需加入<cctype>即可。有几种方法可以做到这一点,但一种简单的方法是将整个字符串转换为小写,然后将第一个字符转换为大写。

// set all characters to lowercase
std::transform(str.begin(), str.end(), str.begin(), std::tolower);

//  Set the first character to upper case.
str[0] = static_cast<std::string::value_type>(toupper(str[0]));

把这一切放在一起你得到的东西看起来有点像这样

#include <iostream>
#include <string>
#include <cctype>

void capitalize(std::string& str)
{
    //  only convert if the string is not empty
    if (str.size())
    {
        // set all characters to lowercase
        std::transform(str.begin(), str.end(), str.begin(), std::tolower);

        //  Set the first character to upper case.
        str[0] = static_cast<std::string::value_type>(toupper(str[0]));
    }
}

int main()
{
    std::string first, last;

    //  Read in the first and last name.
    std::cin >> first >> last;

    //  let's capialize them.
    capitalize(first);
    capitalize(last);

    //  Send them to the console!
    std::cout << first << " " << last << std::endl;
}

注意:包含using namespace std;之类的语句被认为是错误形式,因为它会将std命名空间中的所有内容提取到当前范围内。避免尽可能多。如果您的教授/教师/教师使用它,他们应该受到惩罚,并被迫观看电影“黑客”直到时间结束。

答案 1 :(得分:-1)

由于您使用的是C ++,因此您应该使用std::string而不是char数组,而getline()可以完全按照您的要求使用。

#include <iostream>
#include <string>

int main()
{
    std::string first, last;
    while (std::getline(cin, first, ' '))
    {
         std::getline(cin, last);
         //Convert to upper, lower, whatever
    }
}

如果您只希望每次运行获得一组输入,则可以省略循环。 getline()的第三个参数是分隔符,它将告诉函数在到达该字符时停止读取。默认情况下为\n,因此如果您想要阅读剩下的内容,则不需要包含它。

相关问题