繁体   English   中英

我的向量打印所有元素,但最后一个 C++

[英]My vector prints all elements but last one c++

这对我来说毫无意义。 我对代码做了一些事情,它只在第一次工作。 然后我再次测试它,它返回到不包括向量中的最后一个元素。 我不知道我做错了什么。 请帮忙。

cout << "Enter a sentence: " << endl;

getline(cin, sentence);

for (auto x : sentence) // stores individual words in the vector
{
    if (x == ' ')
    {
        myString.push_back(word);
        cout << word << endl;
        word = " ";
    }
    else
    {
        word = word + x;

    }

}
for (auto elem : myString)
{
    cout << elem << endl;
}

如果最后一个单词后没有空格,则不会将其添加到向量中。

要扫描的sentence一个字母的时间,每个附加信word ,直到你遇到一个空间,只有这样,你插入wordvector 因此,如果sentence不以空格结尾,则不会将最后一个word插入到vector

有几种不同的方法可以解决这个问题:

  1. 检查循环退出后word是否为空,如果不是则将其插入向量中:
cout << "Enter a sentence: " << endl;

getline(cin, sentence);

for (auto x : sentence)
{
    if (isspace(static_cast<unsigned char>(x))
    {
        if (!word.empty())
        {
            myString.push_back(word);
            word = "";
        }
    }
    else
    {
        word += x;
    }
}

if (!word.empty())
{
    myString.push_back(word);
}

for (const auto &elem : myString)
{
    cout << elem << endl;
}
  1. 自己扫描单词边界,例如使用string::find_first_(not_)of()
cout << "Enter a sentence: " << endl;

getline(cin, sentence);

const char* wspace = " \f\n\r\t\v";

size_t start = 0, end;
while ((start = sentence.find_first_not_of(wspace, start)) != string::npos)
{
    end = sentence.find_first_of(wspace, start + 1));
    if (end == string::npos)
    {
        myString.push_back(sentence.substr(start));
        break;
    }

    myString.push_back(sentence.substr(start, end-start));
    start = end + 1;
}

for (const auto &elem : myString)
{
    cout << elem << endl;
}
  1. sentence放入std::istringstream ,然后使用operator>>从中提取完整的空格分隔词。 让标准库为您完成所有繁重的解析工作:
cout << "Enter a sentence: " << endl;

getline(cin, sentence);

istringstream iss(sentence);
while (iss >> word)
{
    myString.push_back(word);
}

for (const auto &elem : myString)
{
    cout << elem << endl;
}

暂无
暂无

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

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