2013-12-10 36 views
1

我有這樣的代碼:使用「函數getline」使用數組

#include <iostream> 
#include <cstring>  // for the strlen() function 

int main() 
{ 
    using namespace std; 

    const int Size = 15; 
    static char name1[Size];     //empty array 
    static char name2[Size] = "Jacob";  //initialized array 

    cout << "Howdy! I'm " << name2; 
    cout << "! What's your name?" << endl; 
    cin >> name1; 
    cout << "Well, " << name1 << ", your name has "; 
    cout << strlen(name1) << " letters and is stored" << endl; 
    cout << "in an array of " << sizeof(name1) << " bytes" << endl; 
    cout << "Your intitial is " << name1[0] << "." << endl; 
    name2[3] = '\0'; 

    cout << "Here are the first 3 characters of my name: "; 
    cout << name2 << endl; 

    cin.get(); 
    cin.get(); 

    return 0; 
} 

的問題

在這段代碼中,唯一的問題是,如果你用空格輸入你的名字,它會跳過姓氏之後的空間。 getline()方法可以解決這個問題,但我似乎無法完成。解決這個問題甚至可能有更好的方法。總而言之,我希望能夠在開始提示時輸入名字和姓氏(一個全名)。

程序

程序簡單地提示,使用輸入他們的名字,然後輸出該用戶名,與以字節爲單位的大小和用戶的姓名的前三個字符沿。

+0

這將是更好地使用'的std :: string'。 – chris

+0

它可能是;不過,我正在嘗試學習如何使用數組來做到這一點。 – Jake2k13

+1

如果這是家庭作業,並且您需要*使用陣列,請繼續。否則,你最好忽略數組並僅使用'std :: string'。 –

回答

2

使用函數getline方法是這樣的:

cout << "! What's your name?" << endl; 
cin.getline(name1, sizeof(name1)); 
cout << "Well, " << name1 << ", your name has "; 

要計算非空格字符:

#include <iostream> 
#include <cstring>  // for the strlen() function 
#include <algorithm> 
int main() 
{ 
    using namespace std; 

    const int Size = 15; 
    static char name1[Size];     //empty array 
    static char name2[Size] = "Jacob";  //initialized array 
    cout << "Howdy! I'm " << name2; 
    cout << "! What's your name?" << endl; 
    cin.getline(name1, sizeof(name1)); 
    cout << "Well, " << name1 << ", your name has "; 
    int sz_nospace = count_if(name1, name1 + strlen(name1), 
      [](char c){return c!=' ';}); 
    cout << sz_nospace << " letters and is stored" << endl; 
    cout << "in an array of " << sizeof(name1) << " bytes" << endl; 
    cout << "Your intitial is " << name1[0] << "." << endl; 
    name2[3] = '\0'; 

    cout << "Here are the first 3 characters of my name: "; 
    cout << name2 << endl; 

    return 0; 
} 
+0

謝謝,這是一個可以接受的答案。但是,有沒有辦法可以省略單詞之間的空格作爲「計數」?我的程序將該空間計爲名稱中的一個字符。有沒有解決的辦法? – Jake2k13

+0

@ Jake2k13,你可以使用count_if,看到更新的答案 – perreal

+0

我認爲如果'count_if'存儲在它自己的語句中而不是打印語句中,這個答案會更好。 –