【问题标题】:splitting words for full name in only one variable仅在一个变量中拆分全名的单词
【发布时间】:2019-03-04 19:05:55
【问题描述】:

我想将一个全名彼此分开。它仅适用于名字。

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

int main()
{
     string FullName;
     int i = 0;
     cout <<"Enter your full name "<<endl;
     getline(cin,FullName);

     while (FullName[i] != ' ')
     {
         cout<<FullName.substr(i,FullName.find(' '))<<endl;;
         i++;
     }

     cout <<endl;
     }
return 0
}

我想将每个名称分隔在单独的行中,如下所示:如果我输入:

     Max Michael Max 

输出应该在一个单独的新行中包含每个名称:

     Max
     Michael
     Max

如何在单独的行中拆分名称?

【问题讨论】:

  • 当您使用调试器一次运行程序并检查i 的值时,在执行程序的每一行之后,您有什么观察结果?
  • 我在这里找不到问题
  • 对不起,我想不出这个问题的算法
  • FullName.substr(i,FullName.find(' '))std::string::substr 的文档中所述,第二个参数是停止生成子字符串的子字符串的长度,而不是索引。
  • 可以使用std::stringstream分割字符串。

标签: c++ string iostream


【解决方案1】:

最简单的方法是在读入名称后使用std::istringstream

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
     string FullName;
     cout <<"Enter your full name "<<endl;
     getline(cin, FullName);
     string namepart;
     istringstream strm(FullName);
     while ( strm >> namepart )
        cout << namepart << '\n';
}

Live Example

【讨论】:

    猜你喜欢
    • 2012-10-09
    • 2016-01-30
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 2018-05-13
    相关资源
    最近更新 更多