gpt4 book ai didi

c - 为什么我在用 C 打印时会得到这个空行?

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:46 26 4
gpt4 key购买 nike

我只是对一个句子进行标记并将其放入堆栈,然后弹出每个标记并打印内容。一切都按应有的方式工作,除了我在打印第一个标记后得到一个空行。它似乎只在我打印 %s 时执行此操作,如果我使用其他任何信息,则信息是垃圾,但我没有得到空白行。我已经尝试了一个小函数来确保去除 fgets 获取的换行符。感谢您的帮助。

#define BUFFER_SIZE 100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// self-referential structure
struct stackNode
{
char *cData;
struct stackNode *pNext;
};

typedef struct stackNode StackNode;
typedef StackNode *StackNodePtr;

// function prototypes
void push( StackNodePtr *pTop, char *cInfo );
char* pop( StackNodePtr *pTop );
int isEmpty( StackNodePtr pTop );
void printStack( StackNodePtr pCurrent );


int main(void)
{
char sInput[BUFFER_SIZE];
StackNodePtr pStack = NULL;
char *pToken = NULL;
int iIndex;

printf("Please enter a word to be tokenized\n");

fgets(sInput, BUFFER_SIZE, stdin);

pToken = strtok(sInput, ", ");

while(pToken != NULL)
{
push(&pStack, pToken);
pToken = strtok(NULL, " ,");
}

while (isEmpty(pStack) == 0)
{
printf("%s\n", pop(&pStack));
}
return 0;
}

// Insert a node at the stack top
void push( StackNodePtr *pTop, char *cInfo )
{
StackNodePtr pNew;

pNew = malloc( sizeof( StackNode ) );

if ( pNew != NULL )
{
pNew->cData = cInfo;
pNew->pNext = *pTop; // insert at top of stack
*pTop = pNew;
}
else
{
printf( "%d not inserted. No memory available.\n", cInfo );
}
}

// Remove a node from the stack top
char* pop( StackNodePtr *pTop )
{
StackNodePtr pTemp;
char *cPopValue;

pTemp = *pTop; // attach a pointer to element to be removed
cPopValue = ( *pTop )->cData;
*pTop = ( *pTop )->pNext; // remove at top of stack
free( pTemp ); // release this memory and set it free!

return cPopValue;
}

int isEmpty( StackNodePtr pTop )
{
return pTop == NULL;
}

最佳答案

当您使用fgets 时,您会读取一行包括 '\n' 最后。当您标记字符串时,此 '\n' 位于最后一个标记中。当您打印此 token 时,您也会打印 '\n'。您应该手动删除它,或使用 scanf

编辑:来自 man fgets:

Reading stops after an EOF or a newline.
If a newline is read, it is stored into the buffer.

关于c - 为什么我在用 C 打印时会得到这个空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9304583/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com