我有一组char
指针char *arrayHolder[20]
。当我尝试循环遍历数组时,如果用户在第二个输入上输入项目,我会得到意外的输出
示例:
input> 1 2 3
1
2
3
input>2 3 4
3
3
3
1
循环导致错误:
for(i = 0; arrayHolder[i] != NULL; ++i) {
printf("%c\n", arrayHolder[i]);
令牌输入代码:
char* token;
char buffer [100];
char input[25000];
int i;
char *tokenHolder[300];
int pos = 0;
while(1) {
printf("repl> ");
fgets(buffer, sizeof(buffer), stdin);
token = strtok(buffer, " ");
while(token != NULL) {
tokenHolder[pos] = token;
token = strtok(NULL, " ");
pos++;
}
答案 0 :(得分:1)
在第二个pos = 0
循环之前初始化while
。
pos = 0; //<-- This.
while(token != NULL)
{
tokenHolder[pos] = token;
token = strtok(NULL, " ");
pos++;
}
在OP遇到新问题后编辑:
Break
首先while
循环,现在它是无限的。为了测试,我在3个周期后将其打破了。char* name[300]
的使用不正确,我已经更正了。int row
确保输入的所有数据都正确填充数组。 printf()
已从%s
更改为%c
,因为char*
已打印,而char
int main() { char* token; char buffer [100]; int i; char *tokenHolder[300]; int pos = 0; int row = 0; while(1) { printf("repl> "); fgets(buffer, sizeof(buffer), stdin); token = strtok(buffer, " "); pos = 0; while(token != NULL){ (tokenHolder + row)[pos] = token; token = strtok(NULL, " "); pos++; } (tokenHolder + row)[pos] = '\0'; for(i =0; (tokenHolder + row)[i] != NULL; ++i){ printf("%s\n", (tokenHolder + row)[i]); } row++; if(row > 2) // Breaking of row exceeds 10. You can enter your suitable condition. break; } return 0; }