簡體   English   中英

如何輸出以姓氏開頭的全名? 如果名字或姓氏由單詞組成怎么辦?

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

我需要一些幫助(C++)

制作一個程序,輸入一次全名,但輸出全名將以姓氏開頭。

我附上了我的代碼,但此代碼只會讀取名字的第一個單詞或姓氏的第一個單詞。 如果名字或姓氏有兩個詞怎么辦? 謝謝你。

<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>

全名程​​序

如果讀取失敗(即未讀取任何字),則輸入流將處於失敗狀態。 因此,解決方案是在每次讀取后測試流狀態。

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

只有當它不為空時,您才應該測試每個名稱和輸出。

我認為這可能就是您的意思,從示例名稱來看:

“第一個中間middle2 ...中間n最后”

你想輸出

“最后,第一個中間......中間-n”。

為此,您可以..

  • 使用std::getline(cin, name)獲取名稱。

使用cin >> name會在遇到空格" "時截斷字符串。 這意味着只在空格之前獲取第一個“單詞”。

為避免這種情況,請使用getline

  • 使用string::find_last_of(" ")

  • 使用string::substr(pos, span)獲取所需的子字符串。

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


這是代碼:

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

示例輸出:

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