c++ - 使用 _tcstok 时发生访问冲突

标签 c++ visual-studio-2008 utf-8 access-violation

我正在尝试使用 _tcstok 标记文件中的行。我能够对该行进行标记化一次,但是当我第二次尝试对其进行标记化时,我遇到了访问冲突。我觉得这与实际访问的值无关,而是与访问位置有关。不过,我不确定还有什么办法可以做到这一点。

谢谢,

戴夫

附注我正在使用 TCHAR 和 _tcstok,因为该文件是 UTF-8。

这是我遇到的错误:

Testing.exe 中 0x63e866b4 (msvcr90d.dll) 的第一次机会异常:0xC0000005:访问冲突读取位置 0x0000006c。

vector<TCHAR> TabDelimitedSource::getNext() {
// Returns the next document (a given cell) from the file(s)
TCHAR row[256]; // Return NULL if no more documents/rows
vector<TCHAR> document;

try{
    //Read each line in the file, corresponding to and individual document
    buff_reader->getline(row,10000);
    }
catch (ifstream::failure e){
        ; // Ignore and fall through
    }

if (_tcslen(row)>0){
    this->current_row += 1;
    vector<TCHAR> cells;
      //Separate the line on tabs (id 'tab' document title 'tab' document body)
     TCHAR *  pch;
     pch = _tcstok(row,"\t");
     while (pch != NULL){
         cells.push_back(*pch);
         pch = _tcstok(NULL, "\t");
     }

    // Split the cell into individual words using the lucene analyzer
    try{
      //Separate the body by spaces
        TCHAR original_document ;
        original_document = (cells[column_holding_doc]);
        try{
            TCHAR * pc;
            pc = _tcstok((char*)original_document," ");
             while (pch != NULL){
                 document.push_back(*pc);
                pc = _tcstok(NULL, "\t");
             }

最佳答案

首先,您的代码是 C 字符串操作和 C++ 容器的混合体。这只会让你陷入困境。理想情况下,您应该将该行标记为 std::vector<std::wstring>

此外,您对 TCHAR 很困惑和 UTF-8。 TCHAR是一种字符类型,根据编译时标志在 8 到 16 位之间“ float ”。 UTF-8 文件使用一到四个字节来表示每个字符。所以,您可能希望将文本保存为 std::wstring对象,但您需要将 UTF-8 显式转换为 wstrings。

但是,如果您只想让任何工作,请专注于您的标记化。您需要存储每个 token 开头的地址(作为 TCHAR* ),但您的 vector 是 TCHAR 的 vector 相反。当您尝试使用 token 数据时,您正在转换 TCHAR s 至 TCHAR*指针,访问冲突的结果不足为奇。你给的AV地址是0x0000006c , 这是字符 l 的 ASCII 码.

  vector<TCHAR*> cells;
  ...
  cells.push_back(pch);

……然后……

    TCHAR *original_document = cells[column_holding_doc];
    TCHAR *pc = _tcstok(original_document," ");

关于c++ - 使用 _tcstok 时发生访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6667326/

相关文章:

Spring 实用程序:properties - can you change the encoding to UTF-8?

sql-server - 我需要从 SQL Server 转储表到 utf-8 中的 csv

c# - C# 中是否有与 IEnumerable<T> 等效的标准 C++?

c++ - 关于派生类成员隐藏基类成员的警告

c++ - 函数返回 -1 和 ~0 之间有很大区别吗?

c++ - 使用 Opencl 在 CPU 和 GPU 上运行 opencv 例程

C++ 字符串下标在运行程序时超出范围

c# - .csv 文件可以用作 Visual Studio 2008 中的数据源吗?

visual-studio - 如何在 Visual Studio 2008 中使用 Visual Studio 2010 C++ 工具?

utf-8 - Dart_NewString期望参数 'str'为有效的UTF-8