您的位置:首页 > 编程语言 > C语言/C++

vc++字符串分割的经典编程

2010-10-21 18:26 267 查看
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int dest[1024] = {0};
void main()
{
char str[1024];
char tmp[100];
int i,j;
cin>>str; //将数据全部读入这个字符数组:"12,34,56,78"
int suzu[1024];

j=0;
char * p = strtok(str,",");
if (p)
{
strcpy(tmp,p);
}
i = atoi(tmp); //将字符串转换为int数字
str[j] = i; j++;
// cout<<j<<' '<<i<<endl;
while (p)
{
p=strtok(NULL,",");
if (p)
{
strcpy(tmp,p);
i = atoi(tmp);
str[j] = i;j++;
// cout<<j<<' '<<i<<endl;
}
}
}
更加简洁的代码:
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int dest[1024] = {0};
void main()
{
char str[1024];
char tmp[100];
int i,j = 0;
cin>>str; //将数据全部读入这个字符数组:"12,34,56,78"
int suzu[1024];
char * p = strtok(str,",");
while (p) //这样写更好了,代码更加简洁...
{
strcpy(tmp,p);
i = atoi(tmp);
str[j] = i;j++;
p=strtok(NULL,",");
}
}


参考资料: 楼主看看还有什么地方需要改进的,分数拿来......
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: