我正在为 C++ 中的家庭作业编写一个字符串标记化程序,它使用指针。但是,当我运行和调试它时,它说我的指针 pStart 无效。我有一种感觉,我的问题存在于我的参数构造函数中,我在下面包含了构造函数和对象创建。
如果您能告诉我为什么它说 pStart 在我调试它时是一个错误的指针,我将不胜感激。
谢谢!
StringTokenizer::StringTokenizer(char* pArray, char d)
{
pStart = pArray;
delim = d;
}
// create a tokenizer object, pass in the char array
// and a space character for the delimiter
StringTokenizer tk( "A test char array", ' ' );
完整的 stringtokenizer.cpp:
#include "stringtokenizer.h"
#include <iostream>
using namespace std;
StringTokenizer::StringTokenizer(void)
{
pStart = NULL;
delim = 'n';
}
StringTokenizer::StringTokenizer(const char* pArray, char d)
{
pStart = pArray;
delim = d;
}
char* StringTokenizer::Next(void)
{
char* pNextWord = NULL;
while (pStart != NULL)
{
if (*pStart == delim)
{
*pStart = '\0';
pStart++;
pNextWord = pStart;
return pNextWord;
}
else
{
pStart++;
}
}
return pNextWord;
}
函数 Next 应该返回指向 char 数组中下一个单词的指针。目前还没有完成。:)
完整的 stringtokenizer.h:
#pragma once
class StringTokenizer
{
public:
StringTokenizer(void);
StringTokenizer(const char*, char);
char* Next(void);
~StringTokenizer(void);
private:
char* pStart;
char delim;
};
完整的 main.cpp:
const int CHAR_ARRAY_CAPACITY = 128;
const int CHAR_ARRAY_CAPCITY_MINUS_ONE = 127;
// create a place to hold the user's input
// and a char pointer to use with the next( ) function
char words[CHAR_ARRAY_CAPACITY];
char* nextWord;
cout << "\nString Tokenizer Project";
cout << "\nyour name\n\n";
cout << "Enter in a short string of words:";
cin.getline ( words, CHAR_ARRAY_CAPCITY_MINUS_ONE );
// create a tokenizer object, pass in the char array
// and a space character for the delimiter
StringTokenizer tk( words, ' ' );
// this loop will display the tokens
while ( ( nextWord = tk.Next ( ) ) != NULL )
{
cout << nextWord << endl;
}
system("PAUSE");
return 0;