【发布时间】:2020-02-13 23:49:02
【问题描述】:
我正在尝试对传递的字符串进行标记,将标记存储在数组中并返回它。我在ubuntu上运行这个。显然,当谈到这种语言时,我被难住了。
示例输入:coinflip 3
我的代码思考过程如下:
take: string
if string = null: return null
else:
while temp != null
token[i++] = temp
temp = get next token
return
这是我目前的解决方案。分隔符是空格。 C 已经有一段时间不是我的强项了。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//Clears the screen and prompts the user
void msg()
{
static int init = 1;
if(init)
{
printf("\e[1;1H\e[2J");
init = 0;
}
printf("%s", "uab_sh > ");
}
//Reads in line
char *readIn(void)
{
char param[101];
fgets(param, 101, stdin);
return param;
}
//parse string - still working out the kinks :)
char **parseString(char *cmd)
{
char delim[] = " ";
char* temp = strtok(cmd, delim);
if (temp == " ")
{
return NULL;
}
else
{
int i = 0;
char** tokens = malloc(3 * sizeof(char*));
while (temp != NULL)
{
tokens[i++] = temp;
temp = strtok(NULL, " ");
}
for (i = 0; i < 3; i++)
{
printf("%s\n", tokens[i]);
}
return tokens;
}
}
//Command
int command(char ** cmd)
{
int pid;
if (cmd[0] != NULL)
{
pid = fork();
if (pid == 0)
{
exit(0);
}
else if (pid < 0)
{
perror("Something went wrong...");
}
}
else
return 1;
}
int main()
{
char *line;
char **cmd;
int stat = 0;
while (1)
{
msg();
line = readLine();
cmd = parseString(line);
stat = command(cmd);
if (stat == 1)
{
break;
}
}
return 0;
}
当前错误:
main.c: In function ‘readIn’:
main.c:24:9: warning: function returns address of local variable [-Wreturn-local-addr]
return param;
^~~~~
main.c: In function ‘parseString’:
main.c:32:11: warning: comparison with string literal results in unspecified behavior [-Waddress]
if (temp == " ")
^~
main.c: In function ‘command’:
main.c:59:9: warning: implicit declaration of function ‘fork’ [-Wimplicit-function-declaration]
pid = fork();
^~~~
main.c: In function ‘main’:
main.c:82:10: warning: implicit declaration of function ‘readLine’; did you mean ‘readIn’? [-Wimplicit-function-declaration]
line = readLine();
^~~~~~~~
readIn
main.c:82:8: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
line = readLine();
^
main.c: In function ‘command’:
main.c:71:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
【问题讨论】:
-
char* temp 是正确的。 strtok 返回一个指针。此外,您必须将 cmd 作为 char* 传递
-
@JB1 这个条件 cmd == 1 是什么意思?
-
@JB1 也不清楚是否可以更改传递的字符串。
-
所以我们不需要实际编译和运行您的代码:它有什么问题?
-
@Vlad 我在另一篇文章中读到 strtok() 返回一个 int。既然你指出了,我就删除它。
标签: c token tokenize c-strings strtok