为什么按回车不执行只换行
晚上好🌙🌙🌙本答案参考ChatGPT-3.5
针对这个问题,有以下一些解决方案:
在scanf语句后加入getchar语句,来把回车字符从缓冲区中读取出来,避免影响后续的输入和输出。
while (scanf("%d", &num) == 1) {
getchar(); //读取回车符
//其他操作...
}
在scanf语句中加入空格来跳过回车符,从而避免回车符对后续输入和输出的影响。
while (scanf("%d ", &num) == 1) {
//其他操作...
}
使用fgets函数来替代scanf函数读取数据,fgets读取数据时会将回车符也一起读取,但可以通过添加逻辑来避免回车符对后续操作的影响。
char input[100];
while (fgets(input, 100, stdin) != NULL) {
num = atoi(input); //将字符串转换为整数
//其他操作...
}
可以使用一个循环读取字符的方法来读取输入的整数,遇到回车符就结束读取。
int num = 0;
char c = getchar();
while (c >= '0' && c <= '9') { //只读取数字字符
num = 10 * num + c - '0';
c = getchar();
}
//其他操作...
修改后的代码如下:
#include
#include
typedef struct ListNode {
int val;
struct ListNode* next;
}ListNode;
void insertNode(ListNode** head, int val) { //插入结点
ListNode* new_node = (ListNode*)malloc(sizeof(ListNode));
new_node->val = val;
new_node->next = *head;
*head = new_node;
}
void printList(ListNode* head) { //遍历链表
while (head) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
void destroyList(ListNode** head) { //销毁链表
ListNode* p = *head;
while (p) {
*head = (*head)->next;
free(p);
p = *head;
}
}
int main() {
ListNode* list1_head = NULL;
ListNode* list2_head = NULL;
int num;
char c;
while (1) {
num = 0;
c = getchar();
while (c >= '0' && c <= '9') { //只读取数字字符
num = 10 * num + c - '0';
c = getchar();
}
if (num == 0) break; //遇到回车符结束读取
if (num % 2 == 0)
insertNode(&list1_head, num);
else
insertNode(&list2_head, num);
}
printList(list1_head);
printList(list2_head);
destroyList(&list1_head);
destroyList(&list2_head);
return 0;
}

