Jake2k13
Jake2k13

Reputation: 231

Using "getline" With Arrays

I have this code:

#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;
}

The Issue

the only issue in this code is that if you type your name with a space, it will skip the last name after the space. The getline() method can solve this, but I can't seem to get it all right. There may even be a better method to solving this. To sum it short, I want to be able to enter both a first and last name (one full name) when prompted from the start.

The program

The program simply prompts and use to input their name, and then outputs the users name, along with size in bytes and the first three characters of the user's name.

Upvotes: 1

Views: 2823

Answers (1)

perreal
perreal

Reputation: 97968

Use getline method like this:

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

To count non-space characters:

#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;
}

Upvotes: 2

Related Questions