c++ - c++中数组只存储token的第一个字符

标签 c++ arrays tokenize

    int main(void)
{
char *text = (char*)malloc ( 100 *sizeof( char));
cout << "Enter the first arrangement of data." << endl;
cin.getline(text, 100);
char *token = strtok(text, " ");
char *data = (char*)malloc ( 100*sizeof( char));
while ( token != NULL )
{
    if (strlen(token) > 0)
    {
        cout << token << endl; // to test if the token is correct so far.
        data[Tcount++] = *token;
    }
    token = strtok(NULL, " ");
}


for(i = 0; i < Tcount; i++)
{
    cout << data[i] << endl;
}  

出于某种原因,当我输入用户输入 xp = a + 1 时,data[i] 的输出是:
x
=
一个
+
1
你知道为什么第一个标记(应该是 xp)只作为 x 存储在 data[] 中吗?
谢谢。

最佳答案

strtok 有一些您没有考虑到的内部状态。看这里:

http://www.cplusplus.com/reference/cstring/strtok/

这一行只抓取 token 的第一个字符:

    data[Tcount++] = *token;

然后这一行跳到下一个标记(由于 strtok 的内部状态记住了最后一个标记的位置):

    token = strtok(NULL, " ");

您需要在包含这两行的 while 循环中嵌套另一个循环,以便读取标记中的所有字符。只有这样你才能在不丢失数据的情况下再次调用 strtok。

关于c++ - c++中数组只存储token的第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30157789/

相关文章:

java - Android MultiAutoCompleteTextView 具有自定义标记器,如 Whatsapp GroupChat

c++ - 如何将初始化列表与基类一起使用?

php检查数组是否为空

c++ - 迭代n维 vector c++

c - 在结构体数组中搜索字符串

arrays - 在多维数组上使用 ubound 的 VBA

python - 如何使用 tokenize 注释器和 pycorenlp(Stanford CoreNLP 的 Python 包装器)执行文本的单词标记,而不使用 ssplit?

java - 在 Java StreamTokenizer 文档中, "ordinary"是什么意思?

c++ - OpenCv 2.3 C - 如何隔离图像中的对象

数组大小为零时的 C++ 内存分配行为