I am new to c, and when reading from stdin I need to separate the words if there is a space. When I type exit I want to print hi but when I use strcmp it always returns false and doesn't print out hi
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define BUFFSIZE 1024
int main()
{
int n;
char buffer [BUFFSIZE];
int pos =0;
char * parse ;
char * buf [BUFFSIZE];
read (STDIN_FILENO, buffer, BUFFSIZE);
parse = strtok(buffer, " ");
while (parse != NULL) {
buf[pos] = parse;
pos++;
//printf( "%s\n", parse );
parse = strtok(NULL, " ");
}
for (int i=0; i<pos; i++) {
if (strcmp(buf[i], "exit") ==0) {
printf("hi");
}
printf("%s\n",buf[i]);
}
} // main
There are several changes you need to make, mostly highlighted in the comments.
strtok()
. You should also check that the read()
worked and returned data.
Those changes lead to something like this:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define BUFFSIZE 1024
#define DELIMITERS " \n\t\r"
int main(void)
{
char buffer[BUFFSIZE + 1]; /* Allow for a null terminator */
int pos = 0;
char *parse;
char *buf[BUFFSIZE];
int nbytes = read(STDIN_FILENO, buffer, BUFFSIZE);
if (nbytes <= 0)
{
fprintf(stderr, "Failed to read anything from standard input\n");
return 1;
}
buffer[nbytes] = '\0';
parse = strtok(buffer, DELIMITERS);
while (parse != NULL)
{
printf("parse [%s]\n", parse);
buf[pos] = parse;
pos++;
parse = strtok(NULL, DELIMITERS);
}
printf("pos = %d\n", pos);
for (int i = 0; i < pos; i++)
{
if (strcmp(buf[i], "exit") == 0)
{
printf("found '%s' at index %d\n", buf[i], i);
}
printf("%s\n", buf[i]);
}
return 0;
}
That includes some diagnostic printing. Note that the message hi
is singularly uninformative, especially as the message did not end with a newline. End messages with newlines at minimum.
With the more extensive delimiters shown, the output looks like:
parse [exit]
pos = 1
found 'exit' at index 0
exit
``
With just blank as a delimiter, the output looked like:
```none
parse [exit
]
pos = 1
exit
Note the extra blank line after exit
.
With a more extensive input string in due course, the keyword exit will be recognized.
, the output is:
parse [in]
parse [due]
parse [course,]
parse [the]
parse [keyword]
parse [exit]
parse [will]
parse [be]
parse [recognized.]
pos = 9
in
due
course,
the
keyword
found 'exit' at index 5
exit
will
be
recognized.
You decide if that's satisfactory. I think the loop should probably end when the match is detected.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.