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/