2013-12-10 37 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'存储在它自己的语句中而不是打印语句中,这个答案会更好。 –