找到第三个子字符串后打印错误消息

printing error message after third substring is found

您好,我是 C++ 的新手。我有一个关于字符串拆分的问题。

比如我有这样一个字符串

std::string str = "jump 110 5";

字符串之间 "jump"、"110" 和 "5" 可以有多少个空格。

我想将 110 保存在一个 int 变量中,如果在数字 110 之后出现另一个数字或字符,则循环应该中断。

到目前为止,我已经删除了所有空格并将 110 保存在一个变量中并打印出来,数字 5 被忽略了。

如何在 110 之后中断或打印一条错误消息,提示该字符串无效?

这是我的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main() {

    std::string str = "jump 110 5";
    size_t i = 0;
    for ( ; i < str.length(); i++ ){ if ( isdigit(str[i]) ) break; }    

    str = str.substr(i, str.length() - i );    

    int id = atoi(str.c_str());
    std::cout<<id;

     return 0;    
}

编辑:第二次尝试.. 这是我写的将值解析为向量的内容。如果向量有不止一组数字,它会打印并出错。

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>


int main() {

    std::string str = "jump 110 5";
    size_t i = 0;
    for (; i < str.length(); i++)
    {
        if (isdigit(str[i]))
            break;
    }

    str = str.substr(i, str.length() - i);


    // Parse str to id
    std::stringstream sstr;
    sstr << str;
    std::string tempStr;
    std::vector<size_t> id;   

    while (std::getline(sstr, tempStr, ' '))
    {
        std::cout << tempStr << std::endl;
        id.push_back(std::stoi(tempStr));
    }

    // print an error if additional numbers are in id
    if (id.size() > 1)
    {
        std::cout << "Error: " << id[1];
    }
    else
    {
        std::cout << "You're good";
    }

    return 0;
}

注意:如果110和5之间有一个以上的空格,则会出错

原答案: 如果你想让 id 的值是 110 5,那么 id 不应该是 int 类型,因为它不能包含空格。如果你想让id的值为1105,那么你需要去掉字符串“110 5”中的空格,然后再赋值给id,否则赋值时会被截断至 id

这就是我去掉空格以使 id 等于 1105 的方法。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>


int main() {

    std::string str = "jump 110 5";
    size_t i = 0;
    for (; i < str.length(); i++)
    {
        if (isdigit(str[i]))
            break;
    }

    str = str.substr(i, str.length() - i);

    // get rid of spaces
    std::string tempStr;
    for (int i = 0; i < str.length(); i++)
    {
        if (str[i] != ' ')
        {
            tempStr.push_back(str[i]);
        }
    }

    // Set the str object to tempStr
    str = tempStr;

    int id = atoi(str.c_str());
    std::cout << id;


    return 0;
}

如果您真的需要将 id 保留为 int 并将 1105 分开,那么我建议将 id 变成a std::vector 并将字符串解析为向量。