c++ - 遍历缺少最后一个字符的字符串

标签 c++ visual-c++

我是 C++ 的新手,正在尝试逐一读取字符串中的每个字符。这是我正在做的:

string sum = "1 + 3 x 2\n";
char delimiter = ' ';
string token = "";
vector<string> tokens;

for(char c: sum)
{
    if(c == delimiter)
    {
        tokens.push_back(token);
        token = "";
    } 
    else 
    {
        token += c;
    }
}

所以我基本上是在标记我的字符串。在我看来,我应该以:

tokens[0] = "1";
tokens[1] = "+";
tokens[2] = "3";
tokens[3] = "x";
tokens[4] = "2";

但是,当我运行它时,我没有得到最后的“2”。我认为这是因为换行(这是必要的,不值得解释)。

为什么会这样?

最佳答案

您应该将分隔符形式从 char 更改为字符串,然后检查 c 是否在该字符串中。

string sum = "1 + 3 x 2\n";
string delimiters = " \n";
string token = "";
vector<string> tokens;

for(char c: sum)
{
    if(delimiters.find(c) != string::npos)
    {
        tokens.push_back(token);
        token = "";
    } 
    else 
    {
        token += c;
    }
}

这也应该考虑到末尾的换行符。

关于c++ - 遍历缺少最后一个字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26578244/

相关文章:

c++ - C++ 是否仍被视为静态类型语言?

c++ - std::strlen 如何在内部工作?

c# - P/Invoke c# 和 native c++

c++ - 如何通过引用正确传递迭代器?

visual-c++ - google::protobuf::io::FileOutputStream 未定义?

mysql - 使用 OCI、MySQL 和 LabView 构建 DLL 一直失败

c++ - 在 Windows 上使用 QT 运行 LibVLC 时禁用命令提示符

c++ - 是否可以颠倒破坏顺序?

c++ - 多态指针的typeid?

c++ - 如何用我的代码编译两个相似的头文件,以便在其上运行 2 个 DLL