简体   繁体   English

strtok函数错误

[英]Error with strtok Function

In my code i get a unhandled expression error when i use parse function. 在我的代码中,当我使用解析函数时,出现unhandled expression error

In my PopStack function is this the right way to delete the last element of vector. 在我的PopStack函数中,这是删除向量最后一个元素的正确方法。

Error is: 错误是:

Unhandled exception at 0x0f463b50 (msvcr100d.dll) in Boost_Test.exe: 0xC0000005: Access violation writing location 0x00345d49. Boost_Test.exe中0x0f463b50(msvcr100d.dll)的未处理异常:0xC0000005:访问冲突写入位置0x00345d49。


class Stack
{
public:
    Stack() {GlobalIndex=0; };
    std::vector<char*> v;
    int GlobalIndex;
    void AddStack(char* txt);
    void Parse();
    void PopStack();
    void PrintStack();

};

void Stack::Parse()
{
    char* tok;
    tok = strtok(v[GlobalIndex-1], ";");

    while(tok!=NULL)
     {
        cout<<"\nThe time value is = "<<tok<<endl;
        tok = strtok(NULL, " ");
     }
}




void Stack::AddStack(char* txt)
{

v.push_back(txt);
GlobalIndex++;

}


 void Stack::PopStack()
  {
   v.pop_back();
   GlobalIndex--;
  }

 void Stack::PrintStack()
 {
 std::cout<<v[GlobalIndex-1]<<endl;
 }


int _tmain(int argc, _TCHAR* argv[])
{
 int i;
 Stack s;
 s.AddStack("aaa;1.2");
 s.AddStack("bbb;1.7;");
 s.AddStack("ccc;2.2");
 s.Parse();  // This gives a unhandled expression error 
 s.PopStack(); 
 s.PrintStack();
 return 0;
}

The end of the token found, in you case the ';', is replaced by a 0. 找到的令牌结尾(在您的情况下为“;”)将替换为0。

This write operation is done on the string literal you pass: 此写操作是在您传递的字符串文字上完成的:

s.AddStack("aaa;1.2");

But the literal is not writable, basically its a 'const char *', hence the access violation. 但是文字是不可写的,基本上是'const char *',因此违反了访问规则。

As advised by other members i have now used c++ strings along with boost library. 正如其他成员所建议的那样,我现在已经使用了c ++字符串和boost库。

#include "stdafx.h"
#include <iostream>
#include <asio.hpp>
#include <regex.hpp>
#include <algorithm/string/regex.hpp>
#include <string>
#include <algorithm/string.hpp>

using namespace std;

class Stack
 {

    public:
    Stack() {GlobalIndex=0; };
    std::vector<std::string> v;
    string s;
    int GlobalIndex;
    void AddStack(std::string);
    void Parse();
    void PopStack();
    void PrintStack();

};

void Stack::Parse()
 {

   std::vector<std::string> result;
   boost::split(result,v[GlobalIndex-1],boost::is_any_of(";"));
   cout<<"\nThe boost split is = "<<result[1]<<endl;
}

void Stack::AddStack(std::string txt)
{

v.push_back(txt);
GlobalIndex++;

}

void Stack::PopStack()
{
v.pop_back();
cout<<v.size()<<endl;
GlobalIndex--;

}

void Stack::PrintStack()
{
std::cout<<v[GlobalIndex-1]<<endl;
}

int _tmain(int argc, _TCHAR* argv[])
 {
int i;
Stack s;
s.AddStack("aaaaaa;1.2");
s.AddStack("bbbbb;1.7;");
s.AddStack("ccccc;2.2");
s.Parse();
s.PopStack();
s.PopStack();
s.PrintStack();
cin>>i;
return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM