简体   繁体   中英

How output a full name that starts with last name? What if the the first name or last name consist of words?

i need some help (C++)

Make a program that will input the full name once but output of full name will start with last name.

I attached my code but this code will read only the first word of first name or first word of last name. What if the first name or last name has two words? Thank you.

<pre>
#include <iostream>
#include <string> 
using namespace std;

main()
{
   string first, middle, last;
   cout << "What is your full name? ";
   cout << endl << "---> ";
   cin >> first >> middle >> last;

   cout << "---> " << last << ", " << first << " " << middle;
   cout << endl;

   return 0;



 }
<code>

full name program

The input stream will be in a failure state if the read fails (ie no word was read). So, the solution is to test the stream state after each read.

if (cin >> first)
{
  if (cin >> middle)
  {
    if (cin >> last)
    {
      //...
    }
    else
    {
      last = middle;
    }
  }
}

You should test each name and output only if it is not empty.

I think this may be what you mean, from an example name :

"first middle middle2 ... middle-n last"

you would like to output

"last, first middle .... middle-n".

To do this, you can..

  • Use std::getline(cin, name) to get the name.

Using cin >> name will truncates the string when it meets a whitespace " " . Which means only get the first "word" before whitespace.

To avoid this, use getline .

  • Use string::find_last_of(" ")

  • Use string::substr(pos, span) to get the desired substring.

http://www.cplusplus.com/reference/string/string/substr/


Here is the code :

#include <iostream>
    #include <string> 
    using namespace std; 
    int main() { 
        string name, last; 
        cout << "What is your full name? "; 
        cout << endl << "---> "; 
        getline(cin,name);
        int idx;
        idx = name.find_last_of(" ");
        cout << idx << endl;
        last = name.substr(idx+1);
        cout << "---> " << last << ", " << name.substr(0, idx);
         cout << endl; return 0; }

Example output :

What is your full name :
---> first middle middle2 middle3 last
28
---> last, first middle middle2 middle3

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