不使用scanf与sscanf生成以下代码 #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct LNode { int data; struct LNode* next; } LNode, *Linklist; int main(){ char buffer[10]; // 存放每次读入的一行字符 int k=0,length=1; Linklist head = (LNode*)malloc(sizeof(LNode)); Linklist temp_head = (LNode*)malloc(sizeof(LNode)); if(!head || !temp_head){ printf("Memory allocation failed.\n"); return -1; } head ->next=NULL; temp_head->next=NULL; Linklist rear=head,temp_rear=temp_head; printf("Please input elements line by line(enter \"end\" to stop):\n"); while(fgets(buffer,sizeof(buffer),stdin)!=NULL){ if(strcmp(buffer,"end\n")==0) break; sscanf(buffer,"%d",&k); if(length++ %2!=0 ){ Linklist p=(LNode *) malloc(sizeof(LNode )); if(!p){ printf("Memory allocation failed.\n"); break; } p->data=k;p->next=NULL;rear->next=p;rear=p; } else{ Linklist p=(LNode *) malloc(sizeof(LNode )); if(!p){ printf("Memory allocation failed.\n"); break; } p->data=k;p->next=NULL;temp_rear->next=p;temp_rear=p; } } rear->next = temp_head->next ; printf("List: "); for(Linklist p = head->next ;p != NULL; p = p->next ) printf("%d ",p->data ); printf("\n"); free(head );free(temp_head ); return 0 ; }
时间: 2025-06-26 14:05:06 浏览: 10
为了替换掉 `scanf` 和 `sscanf` 函数,并仍然能够从输入字符串中解析出整数数据,我们可以采用 C 标准库中的其他函数如 `strtol()` 或手动处理字符数组的方式来进行转换。
以下是修改后的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct LNode {
int data;
struct LNode* next;
} LNode, *Linklist;
// 将字符串转为数字的功能替代 sscanf 使用 strtol()
int string_to_int(const char *buffer) {
char *endptr;
long result = strtol(buffer, &endptr, 10);
if (*endptr == '\n' || *endptr == ' ' || *endptr == '\0') {
return (int)result; // 成功转换返回结果
}
return -1; // 如果无法成功转换则返回错误码
}
int main() {
char buffer[50];
int k = 0, length = 1;
Linklist head = (LNode *)malloc(sizeof(LNode));
Linklist temp_head = (LNode *)malloc(sizeof(LNode));
if (!head || !temp_head) {
printf("Memory allocation failed.\n");
return -1;
}
head->next = NULL;
temp_head->next = NULL;
Linklist rear = head, temp_rear = temp_head;
printf("Please input elements line by line(enter \"end\" to stop):\n");
while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
if (strcmp(buffer, "end\n") == 0)
break;
k = string_to_int(buffer); // 替代了 sscanf 的功能
if (length++ % 2 != 0) { // 奇数位置的数据插入主链表
Linklist p = (LNode *)malloc(sizeof(LNode));
if (!p) {
printf("Memory allocation failed.\n");
break;
}
p->data = k;
p->next = NULL;
rear->next = p;
rear = p;
} else { // 偶数位置的数据插入临时链表
Linklist p = (LNode *)malloc(sizeof(LNode));
if (!p) {
printf("Memory allocation failed.\n");
break;
}
p->data = k;
p->next = NULL;
temp_rear->next = p;
temp_rear = p;
}
}
rear->next = temp_head->next;
printf("List: ");
for (Linklist p = head->next; p != NULL; p = p->next)
printf("%d ", p->data);
printf("\n");
free(head);
free(temp_head);
return 0;
}
```
### 修改说明:
1. **去掉 `sscanf`**:通过自定义的辅助函数 `string_to_int` 来代替原来的 `sscanf` 功能。
2. **改进内存管理**:当分配失败时立即中断程序避免潜在的风险。
阅读全文
相关推荐


















