您可以直接讀入std::string
的名字和姓氏。沒有理由自己管理緩衝區或猜測它們將會或應該是多大。這可以用的東西就像這樣
std::string first, last;
// Read in the first and last name.
std::cin >> first >> last;
你會希望將字符串轉換爲根據您的要求大/小寫。這可以通過在C++標準庫中提供的std::toupper
和std::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
命名空間到當前範圍報表。避免儘可能多。如果你的教授/教師/教師使用它,他們應該受到懲罰,並被迫觀看電影黑客直到時間結束。
也許有一些角色可以分隔您可以查找的名字和姓氏? – cdhowie 2014-10-26 19:08:41