因此,我试图使用read()获取用户的输入。while循环运行,直到在linux终端中输入ctrl+d并停止输入。我编写了一些代码并运行,但我遇到的问题是,我不知道如何准确地获取输入中的内容以及如何使用它。
在下面的代码中,在if(buff[offset] == '\n')之后(运行给定的输入,并在它完成后清除缓冲区并转移到下一个输入),我不知道如何进入3种可能的输入情况,也不知道如何从第二种情况中获得数字:
sure.)
buff[offset-1]应该得到这个数字,但我不是完全的buff[offset-1]-打印一个消息。)
代码:
int fd = 0; // set read() to read from STDIN_FILENO, because it's number is 0
const size_t read_size = 1; // set chunk size
size_t size = read_size;
size_t offset = 0;
size_t res = 0;
char *buff = malloc(size+1);
*buff = '\0';
while((res = read(fd, buff + offset, read_size)) > 0) // read from stdin and save to buff
{
if(buff[offset] == '\n')
{ // THIS PART
buff[offset] = '\0';
if(buff == "e")
{
// exit the program
return 0;
}
else if(buff == "p")
{
// do sth
}
else
{
// print a message
}
// reset the buffer (free its memory and allocate new memory for the next input)
offset = 0;
size = read_size;
free(buff);
buff = NULL;
buff = malloc(size + 1);
*buff = '\0';
}
else
{
offset += res;
buff[offset] = '\0';
if (offset + read_size > size)
{
size *= 2;
buff = realloc(buff, size+1);
}
}
}如果用read()无法做到这一点,我可以尝试使用类似fget()之类的东西吗?
发布于 2022-02-28 18:37:14
if(buff == "p")
这一行检查字符串buff是否存储在与字符串"p"相同的地址。但是,您不希望检查字符串是否存储在相同的地址,但它们是否具有相同的内容。
...strcmp()如何工作..。
使用strcmp(),您可以检查两个字符串是否相同:
if(!strcmp(buff, "e"))"p“.既然N可能是任何数字?
只需检查buff的第一个字符是否为'p'
if(buff[0] == 'p')请注意,字符常量(与字符串常量相反)使用单引号(')代替双引号(")。
发布于 2022-03-01 01:01:09
正如我在上面的评论中所描述的,这里有一个完整的答案:
int main(void)
{
char line[100], cmd;
int num, cnt;
while(fgets(line,sizeof(line),stdin)) != EOF) {
cnt = sscanf(line," %c %d",&cmd,&num);
if (cnt == 0) {
// empty line, no command
} else if (cmd == 'e') {
// exit the program
break;
} else if (cmd == 'p' && cnt == 2) {
// no something with num
} else {
// print a message
}
}
return 0;
}https://stackoverflow.com/questions/71298988
复制相似问题