将字符串中的每个单词输出到新行

Output each word in string to a new line

本文关键字:单词 输出 新行 字符串      更新时间:2023-10-16

我正在设计一个函数,它有一个输入参数:字符串。该函数获取该字符串的内容,并将每个单词输出到新行。目前,这个函数除了输出字符串中的最后一个单词外,什么都做。这是功能代码:

void outputPhrase(string newPhrase)
{
    string ok;
    for (int i = 0; i < newPhrase.length(); i++)
    {
        ok += newPhrase[i];
        if (isspace(newPhrase.at(i)))
        {
            cout << ok << endl;
            ok.clear();
        }
    }
}

试试这个:

 for (int i = 0; i < newPhrase.length(); i++)
    {
        ok += newPhrase[i];
        if (isspace(newPhrase.at(i)) || i==newPhrase.length()-1)
        {
            cout << ok << endl;
            ok.clear();
        }

    }

你可以使用这个函数来完成你的任务,

void split(string newPhrase)
{
    istringstream iss(newPhrase);
    do
    {
        string sub;
        iss >> sub;
        cout << sub << endl;
    } while (iss);
}

请记住包括<string>和<代码中的sstream>。