【发布时间】: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];