关于字符串分割的问题
我又一串字符:9307|43213|51|58|17|0|1|1|1089想把每个以“|”分割的数直接转换成int型,该怎样做?
用sscanf(“9307|43213|51|58|17|0|1|1|1089”,"%d|%d|%d|%d|%d|%d|%d|%d|%d", &a,&b。。。。)不行呀!!!
请教各位大虾,谢了!
#include <iostream> #include <string> #include <cstdlib> using namespace std; int main() { string str; cout<<"please input a string :"<<endl; cin>>str; string* temp; int n=str.length(); int k=0; for(int i=0;i<n;i++) if(str[i]=='|') k++; temp=new string[k+1]; int j=0,s=0; for(int i=0;i<n;i++) { if(str[i]=='|') { temp[j]=str.substr(s,i-s); j++; s=i+1; } if(i==n-1) temp[j]=str.substr(s,n-s); } int *a=new int[j+1]; for(int d=0;d<=j;d++) { a[d]=atoi(temp[d].c_str()); cout<<a[d]<<endl; } }
using namespace std; int main() { string str,tmp; cin >> str; for (int i = 0; i != str.size(); i++) { if (str[i] != '|') tmp += str[i]; else { cout << atoi(tmp.c_str()) << endl; tmp = ""; } } if (tmp != "") cout << atoi(tmp.c_str()) << endl; return 0; }