简体   繁体   中英

How do i take the initials of all the parts of one's name except the last name?

Hi i am trying to write a c++ program where the user will enter a name lets say for example: Tahmid Alam Khan Rifat and the computer will print the formatted version of the name which in this case will be: Mr. TAK Rifat. I have included the code below. You will be able to see that I got close but still not exactly what i wanted. Please help.

#include<iostream>

#include<string>

using namespace std;

class myclass{

private:

string name,temp;

    string p;

int i,j,sp;

public:
    void work(){

        cout << "Enter the name of the male student: ";
        getline(cin,name);
        cout << endl;
        cout << "The original name is: ";
        cout << name;
        cout << endl << endl;

        cout << "The formatted name is: " << "Mr." << name[0] << ".";
        for(i=0;i<name.size();i++){
            if(name[i]==' '){
                sp=i;
                for(j=sp+1;j<=sp+1;j++){
                temp=name[j];
                cout << temp << ".";
            }
        }
    }
        for(i=sp+2;i<name.size();i++){
            cout << name[i];
        }
        cout << endl;

    }
};

int main(){
    myclass c;
    c.work();
}

I hope this helps :) It is probably a simpler version (originally I wrote this in C, you could easily convert it to C++ though, since the logic remains the same). I have accepted the name and then inserted a space at the beginning of the string and one more space at the end, before the NULL character ('\\0')

The program checks for a space. When it encounters one, it checks for the next space that occurs in the string. Now occurrence of this space helps us to identify an important determining factor as to what the next action should be.

See, if there is an null character after this subsequent space, then we can conclude that the subsequent space was the one we inserted at the end of the string. That is, the space which occurs after the primary space, which came before the surname. Bingo! You get the precise index of the array, from where the surname starts! :D

Looks long, but really is simple. Good luck!

    #include<stdio.h>
    #include<string.h>
    void main()
    {
        char str[100]; /*you could also allocate dynamically as per your convenience*/
        int i,j,k;
        printf("Enter the full name: ");
        gets(str);

        int l=strlen(str);

        for(i=l;i>=0;i--)
        {
         str[i+1]=str[i]; //shifting elements to make room for the space 
        }

        str[0]=' ';                   //inserting space in the beginning
        str[l+1]=' '; str[l+2]='\0';  //inserting space at the end

        printf("The abbreviated form is:\n");



        for(i=0;i<l+1;i++)                            //main loop for checking
        {
           if(str[i]==' ')                            //first space checker
            {
                for(j=i+1; str[j]!=' ';j++)           //running loop till subsequent space
                {
                }
                if(str[j+1]!='\0')                    //not the space after surname
                {
                    printf("%c.",str[i+1]);           //prints just the initial
                }
                else
                for(k=i+1;str[k]!='\0';k++)           //space after surname
                {
                    printf("%c", str[k]);             //prints the entire surname
                }
            }
        }



    }

Change your loop to the following:-

for(i=0;i<name.size();i++)
{
    if(name[i]==' ')
    {
        initial = i + 1;          //initial is of type int.
        temp = name[initial];     //temp is char.
        cout << temp << ".";
    }
}

Try ravi's answer to make your code work, but I wanted to point out that there are more intuitive ways to program this which would make maintenance and collaboration easier in the future (always a good practice).

You can use an explode() implementation (or C's strtok()) to split the name string into pieces. Then just use the first character of each piece, disregarding the last name.

I think your question has already been answered. But in the future you could consider splitting up your program into more simple tasks, which makes things easier to read. Coupled with descriptive variable and function names, it can make a program easier to comprehend, and therefore to modify or fix later on. Disclaimer - I am a beginner amateur programmer and this is just for ideas:

#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>

// I got this function from StackOverflow somewhere, splits a string into
// vector of desired type:
template<typename T>
std::vector<T> LineSplit(const std::string& line) {
    std::istringstream is(line);
    return std::vector<T>(std::istream_iterator<T>(is), std::istream_iterator<T>());
}
class Names {
 private:
    std::vector<std::string> full_name_;

    void TakeInput() {
        std::cout << "Enter the name of the male student: " << std::endl;
        std::string input;
        getline(std::cin,input);
        full_name_ = LineSplit<std::string>(input);
    }
    void DisplayInitialsOfFirstNames() const {
        std::cout << "Mr. ";
        for (std::size_t i = 0; i < full_name_.size()-1; ++i) {
            std::cout << full_name_[i][0] << ". ";
        }
    };
    void DisplayLastName() const {
        std::cout << full_name_.back() << std::endl;
    }
public:
    void work() {
        TakeInput();
        DisplayInitialsOfFirstNames();
        DisplayLastName();
    };
};
int main(){
    Names n;
    n.work();
}

I guess the easiest way to solve this is to tokenize your string, print the first character from it, except from the last, where you print its full size.

To tokenize, you can do something like that:

std::vector<std::string> tokenize(std::istringstream &str)
{
    std::vector<std::string> tokens;
    while ( !str.eof() ) {
            std::string tmp;
            str >> tmp;
            tokens.push_back(tmp);
    }
    return tokens;
}

Now you can easily transverse the tokens:

int main()
{
    std::string name;

    cout << "Enter the name of the male student: ";
    getline(cin,name);
    cout << endl;

    cout << "The original name is: ";
    cout << name;
    cout << endl << endl;

    std::istringstream str(name);

    std::vector<std::string> tokens = tokenize(str);

    for ( int i = 0 ; i < tokens.size() - 1; ++i)
            std::cout << tokens[i][0] << ". ";

    cout << tokens[tokens.size() - 1] << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM