我试图在C ++中使用strtok来获取字符串的标记。但是,我看到在5个运行的一个中,函数返回的标记是不正确的。有人可以,建议可能是什么问题?
重现我面临的问题的示例代码:
<script>
var app = angular.module("ZenHaberApp", []);
app.controller("WeatherController", function ($scope, $http) {
var $city = document.getElementById("cityName").innerHTML
alert($city)
$http.get('http://localhost:62747/api/getweatherbycityname/' + $city).
success(function (data, status, headers, config) {
$scope.weathers = data.condition_temp;
}).
error(function (data, status, headers, config) {
alert(status);
});
});
</script>
示例输出:
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
#define DEBUG(x) cout<<x<<endl;
void split(const string &s, const char* delim, vector<string> & v)
{
DEBUG("Input string to split:"<<s);
// to avoid modifying original string first duplicate the original string and return a char pointer then free the memory
char * dup = strdup(s.c_str());
DEBUG("dup is:"<<dup);
int i=0;
char* token = strtok(dup,delim);
while(token != NULL)
{
DEBUG("token is:"<<string(token));
v.push_back(string(token));
// the call is treated as a subsequent calls to strtok:
// the function continues from where it left in previous invocation
token = strtok(NULL,delim);
}
free(dup);
}
int main()
{
string a ="MOVC R1,R1,#434";
vector<string> tokens;
char delims[] = {' ',','};
split(a,delims,tokens);
return 0;
}
正如您在第二轮中看到的,创建的令牌是mayank@Mayank:~/Documents/practice$ ./a.out
Input string to split:MOVC R1,R1,#434
dup is:MOVC R1,R1,#434
token is:MOVC
token is:R1
token is:R1
token is:#434
mayank@Mayank:~/Documents/practice$ ./a.out
Input string to split:MOVC R1,R1,#434
dup is:MOVC R1,R1,#434
token is:MO
token is:C
token is:R1
token is:R1
token is:#434
而不是MO C R1 R1 #434
我也尝试检查库代码,但无法弄清楚错误。请帮忙。
EDIT1:我的gcc版本是:MOVC R1 R1 #434
答案 0 :(得分:9)
char delims[] = {' ',','};
应该是
char delims[] = " ,";
您传递的是字符列表而不是带有要使用的分隔符列表的char *
,因此会出现意外行为,因为strtok
需要以0结尾的字符串。在你的情况下,strtok
“在树林里”并在声明的数组之后用任何东西标记。