need help with parsing string
I need some help with parsing a line of text. The line of text being parsed is user input.
I am trying to parse something that has a pipe in it.
For example: hello world | one two
I can get the words before the pipe to go into ArgList. But can't figure out how to get words after the pipe into ArgList2. The pipe symobol does not need to be stored anywhere.
Basically, how do I get the following?
ArgList[0] = hello
ArgList[1] = world
ArgList2[0] = one
ArgList2[1] = two
int main(void)
{
char *ArgList[MAX_ARG_LENGTH];
char *ArgList2[M开发者_如何转开发AX_ARG_LENGTH];
char buf[MAX_BUF_LENGTH];
int i = 0
printf("> ");
if(!fgets(str, MAX_BUF_LENGTH, stdin))
perror("fgets error");
ArgList[i] = strtok(bufstr, " \n");
while(ArgList[i] != NULL)
{
printf("%s", ArgList[i]);
i++;
ArgList[i] = strtok(NULL, " \n");
}
return 0;
}
Any suggestions would be appreciated. Should I first tokenize the whole user input string into ArgList and then move everything after the pipe symbol into ArgList2?
What is the best way to go about this?
I would do something like this:
#include <stdio.h>
#include <string.h>
int main(void)
{
char buf[30] = "hello world | one two";
char *str = buf;
char *str1 = strsep(&str, "|");
char *str2 = strsep(&str, "\n");
printf("\nstr1 = %s and str2 =%s \n", str1, str2);
return 0;
}
NOTE: you should now figure out how you want things your way.
Try using scanf()
.
#include <stdio.h>
#include <string.h>
int main()
{
char args1[NUMBER_OF_RECORDS][MAX_BUF_LENGTH];
char args2[NUMBER_OF_RECORDS][MAX_BUF_LENGTH];
char buf[MAX_BUF_LENGTH];
char buf2[MAX_BUF_LENGTH];
int i = 0;
while (scanf("%s | %s", buf1, buf2)) {
strcpy(args1[i], buf1);
strcpy(args2[i], buf2);
i++;
}
/* Do something with args1 or args2 */
return 0;
}
No guarantees that this code works 100% correctly. Also, scanf()
is prone to errors, so use it with caution.
精彩评论