如何将字符串中的所有数字逐个读入数组(c+;+;) 我看到了类似的问题,但是答案在我的Visual C++ 6上没有用。 我有一个cstring(VisualC++的字符串类),用逗号分隔的数字: CString szOSEIDs = "5,2,6,345,64,643,25,645";
我想把它们一个接一个地放到一个int数组中。 我尝试了stringstream,但它只给出了第一个int。 有人能帮忙吗 附言。 这是我失败的尝试:如何将字符串中的所有数字逐个读入数组(c+;+;) 我看到了类似的问题,但是答案在我的Visual C++ 6上没有用。 我有一个cstring(VisualC++的字符串类),用逗号分隔的数字: CString szOSEIDs = "5,2,6,345,64,643,25,645";,c++,visual-c++,string,C++,Visual C++,String,我想把它们一个接一个地放到一个int数组中。 我尝试了stringstream,但它只给出了第一个int。 有人能帮忙吗 附言。 这是我失败的尝试: std::string input; input = (LPCTSTR)szOSE_IDs; // convert CString to string std::stringstream stream(input); while(1) { int n; stream >> n; if(!stream) bre
std::string input;
input = (LPCTSTR)szOSE_IDs; // convert CString to string
std::stringstream stream(input);
while(1) {
int n;
stream >> n;
if(!stream)
break;
szSQL.Format("INSERT INTO TEMP_TABELA (OSE_ID) values (%d)", n); // I create SQL from my IDs now available
if(!TRY_EXECUTE(szSQL)) //This just a runner of SQL
return false;
}
在这种情况下,我只会得到第一个数字(5),并且只会运行第一个SQL。
有什么想法吗?
谢谢你parse(CString&s,std::vector*v)
{
int l=s.size();//或类似的内容
int res=0;
对于(int i=0;i推回(res);
res=0;
继续;
}
res*=10;
res+=s[i]-'0';
}
v->推回(res);
}
int main()
{
CString s=“1,2,3,4,15,45,65,78”;
std::向量v;
解析(s,&v);
//...
返回0;
}
问题在于流>>n
在点击字符串中的,
时失败。您不能用这种方式对字符串进行标记——相反,请查看一个库,例如boost,它提供了一个很好的标记器
但是,如果您可以保证字符串始终如下所示,您可以尝试:
int n;
while (stream >> n)
{
// Work with the number here
stream.get(); //skip the ","
}
这将使您无需拉动增压等。typedef size\u t pos;
typedef size_t pos;
pos p;
string str("5,2,6,345,64,643,25,645");
string chopped(str);
string strVal;
bool flag = 1;
do{
p = chopped.find_first_of(",");
if(p == chopped.npos)
flag = 0;
strVal = chopped.substr(0,p);
chopped = chopped.substr(p+1);
//cout << chopped << endl;
cout << strVal << endl;
}while(flag);
p位;
字符串str(“5,2,6345,643,25645”);
弦切碎(str);
字符串字符串;
布尔标志=1;
做{
p=切碎。首先查找(“,”)中的\u;
if(p==切碎的.npos)
flag=0;
strVal=scpped.substr(0,p);
切碎的=切碎的。substr(p+1);
//coutCString nums=_T(“5,2,6345,643,25645”);
CString-num;
std::矢量intv;
int pos=0;
做{
if((num=nums.Tokenize(_T(“,”,pos))!=_T(“)
内部推回(_ttoi(num));
其他的
打破
}虽然(正确);
谢谢!看起来它现在可以工作了!还有一点测试要做,我会报告回来这是我的情况下最容易工作的一个(至少现在),所以我给它正确的位置:)Mihran的也很有趣…我也记下了你的答案,现在它作为备份写在我的助手类中。谢谢大家!
typedef size_t pos;
pos p;
string str("5,2,6,345,64,643,25,645");
string chopped(str);
string strVal;
bool flag = 1;
do{
p = chopped.find_first_of(",");
if(p == chopped.npos)
flag = 0;
strVal = chopped.substr(0,p);
chopped = chopped.substr(p+1);
//cout << chopped << endl;
cout << strVal << endl;
}while(flag);
CString nums = _T("5,2,6,345,64,643,25,645");
CString num;
std::vector<int> intv;
int pos = 0;
do {
if ((num = nums.Tokenize(_T(","), pos)) != _T(""))
intv.push_back(_ttoi(num));
else
break;
} while (true);