简体   繁体   English

如何输出以姓氏开头的全名? 如果名字或姓氏由单词组成怎么办?

[英]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++)我需要一些帮助(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" “第一个中间middle2 ...中间n最后”

you would like to output你想输出

"last, first middle .... middle-n". “最后,第一个中间......中间-n”。

To do this, you can..为此,您可以..

  • Use std::getline(cin, name) to get the name.使用std::getline(cin, name)获取名称。

Using cin >> name will truncates the string when it meets a whitespace " " .使用cin >> name会在遇到空格" "时截断字符串。 Which means only get the first "word" before whitespace.这意味着只在空格之前获取第一个“单词”。

To avoid this, use getline .为避免这种情况,请使用getline

  • Use string::find_last_of(" ")使用string::find_last_of(" ")

  • Use string::substr(pos, span) to get the desired substring.使用string::substr(pos, span)获取所需的子字符串。

http://www.cplusplus.com/reference/string/string/substr/ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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