2014-10-26 83 views
-1

如何寫一個C程序來讀取您的名字和姓氏,並將它們轉換爲大寫和小寫字母......我知道上下字母是多麼的多,但是dk如何對於第一個和最後names..any 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; 
} 
+1

也許有一些角色可以分隔您可以查找的名字和姓氏? – cdhowie 2014-10-26 19:08:41

回答

1

您可以直接讀入std::string的名字和姓氏。沒有理由自己管理緩衝區或猜測它們將會或應該是多大。這可以用的東西就像這樣

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

由於您使用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,因此如果您想要閱讀該行的其餘部分,則不需要包含它。