我有一个这样的数字/字符串(我不知道如何将int转换为字符串和从字符串转换)
000000122310200000223340000700012220000011411000000011011271043334010220001127100003333201000001000070005222500233400000000000000000000
我需要做的是将0之间的数字分开,所以我得到像
这样的字符串“12231” “22334” “7” “1222”
依此类推,然后我需要将它们转换为int。 (基本上我已经搜索过如何进行转换无效)
有人可以帮忙吗?
谢谢!
答案 0 :(得分:2)
std::getline
采用可选的分隔符。通常情况下,这将是换行符(因此是getline),但您可以使用0
。
答案 1 :(得分:1)
解决方案std::getline读数为' 0'
// First create a string stream with you input data
std::stringstream ss("000000122310200000223340000700012220000011411000000011011271043334010220001127100003333201000001000070005222500233400000000000000000000");;
// Then use getline, with the third argument it will read untill zero character
// is found. By default it reads until new line.
std::string line;
while(std::getline(ss, line, '0')) {
// In case there are no data, two zeros one by one, skip this loop
if ( line.empty() )
continue;
// now parse found data to integer
// Throws excepions if bad data, consult: http://en.cppreference.com/w/cpp/string/basic_string/stol
int n = std::stoi(line);
std::cout << n << "\n";
}
答案 2 :(得分:1)
如果C ++ 11对你有好处,那么这应该可行
#include <vector>
#include <string>
#include <sstream>
std::vector<int> split(const std::string& s, char delim)
{
std::vector<int> res;
std::stringstream ss(s);
std::string sub;
while (std::getline(ss, sub, delim))
{
int val = std::stoi(sub); // c++11
res.push_back(val);
}
return res;
}
答案 3 :(得分:0)
只需从字符串中进行迭代,然后检查它是否&#39; 0&#39; 0&#39; 0或不。
#include<bits/stdc++.h>
using namespace std;
int main() {
char a[] = "000000122310200000223340000700012220000011411000000011011271043334010220001127100003333201000001000070005222500233400000000000000000000";
vector<int> nums;
int tmp = 0;
for(int i=0;a[i];i++) {
if(a[i] != '0') {
tmp *= 10;
tmp += a[i]-'0';
} else {
if(tmp != 0){
nums.push_back(tmp);
tmp = 0;
}
}
}
for(int i=0;i<nums.size();i++)
cout << nums[i] << endl;
}
答案 4 :(得分:0)
这是一个可能的解决方案:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
std::vector<int> split(const std::string& x, char separator)
{
std::stringstream stream(x);
std::vector<int> numbers;
std::string line;
while(std::getline(stream, line, separator)) {
if (!line.empty()){
int n = std::stoi(line);
numbers.push_back(n);
}
}
return numbers;
}
int main()
{
std::string myStringValue("000000122310200000223340000700012220000011411000000011011271043334010220001127100003333201000001000070005222500233400000000000000000000");
std::vector<int> values = split(myStringValue,'0');
for(auto i : values) {
std::cout << i << std::endl;
}
}