【问题标题】:seperating a single string into seperate variables c++将单个字符串分成单独的变量c ++
【发布时间】:2020-07-30 16:21:27
【问题描述】:

在我的程序中,我收到一个字符串:“09:07:38,50,100” (数字会变化,只有逗号是一致的)

我想要的输出是将字符串分成 3 个不同的变量以用于其他事情。

像这样:

a = 09:07:38

b = 50

c = 100

目前我尝试通过逗号分隔来拆分字符串,但我仍然缺乏将数据放入不同变量的能力,或者至少不知道如何做。 这是我当前的代码:

#include<iostream>
#include<vector>
#include<sstream>

int main() {
    std::string my_str = "09:07:38,50,100";
    std::vector<std::string> result;

    std::stringstream s_stream(my_str); //create string stream from the string

    while(s_stream.good()){
        std::string substr;
        getline(s_stream, substr, ','); //get first string delimited by comma
        result.push_back(substr);
    }

    for(int i = 0; i<result.size(); i++){ //print all splitted strings
        std::cout << result.at(i) << std::endl; 
    }

}

感谢任何帮助,谢谢!

【问题讨论】:

  • 您希望存储数据的变量的类型是什么? (即 a,b,c)
  • 我希望它们存储为字符串 std::string a = ""; std::string b = ""; std::string c = "";
  • 请注意,您的阅读循环遇到了与this 相同的问题。
  • std::string a = result[0] 等。也许在那之前检查result.size() == 3。您还可以将它们转换为数字,例如double a = std::stod(input)
  • 在我看来你想要的只是std::string a = result[0];

标签: c++ string split comma


【解决方案1】:

我认为使用正则表达式解决这类问题是个好主意:

#include <string>
#include <boost\regex.hpp>

int main()
{
    std::string my_str = "09:07:38,50,100";

    std::string a,b,c;

    boost::regex regEx("(\\d{2}:\\d{2}:\\d{2}),(\\d*),(\\d*)");

    if(boost::regex_match(my_str, regEx, boost::match_extra))
    {
        boost::smatch what;
        boost::regex_search(my_str, what, regEx);

        a = what[1];
        b = what[2];
        c = what[3];
    }

    std::cout<< "a = " << a << "\n";
    std::cout<< "b = " << b << "\n";
    std::cout<< "c = " << c;
}

【讨论】:

    【解决方案2】:

    stoi 函数是您所需要的。

    a = stoi(result.at(i));
    std::cout << a;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      • 2015-08-17
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      相关资源
      最近更新 更多