使用“getline”与数组

时间:2013-12-10 03:43:38

标签: c++ visual-c++

我有这段代码:

#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()方法可以解决这个问题,但我似乎无法做到这一点。甚至可能有更好的方法来解决这个问题。总结一下,我希望能够从一开始就提示输入名字和姓氏(一个全名)。

程序

程序只是提示并使用输入其名称,然后输出用户名,以及字节大小和用户名的前三个字符。

1 个答案:

答案 0 :(得分: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;
}