c - 我需要能够从标准输入中读取字符串
问题描述
我正在尝试从标准输入读取一些数据。它将是由空格分隔的数字(任何数字)。问题是我事先不知道长度。我希望能够从标准输入读取并使用它来操作某些东西,这会重复直到按下 ^d。
#include <stdio.h>
#include <stdlib.h>
int
main(){
char input[] = scanf("%s", &input);
for(int i=0; i<sizeof(&input);i++){
//Do something
}
}
这不起作用,但我怎样才能改变它以使其工作?
解决方案
这里的主要问题是你事先不知道元素的数量,在这种情况下你需要预留空间来使用动态内存来存储元素,你可以使用队列或者你可以使用realloc
,也避免scanf
这样使用,总是限制字符串的长度:
char str[100];
scanf("%99s", str); /* buffer overflow protection */
并始终检查结果:
if (scanf("%99s", str) != 1) {
/* something went wrong */
}
使用fgets
(作为替代scanf
)和的示例strtol
,将数据存储在队列中:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
struct node {
struct node *next;
int data;
};
void *enqueue(struct node **root, int data)
{
struct node *node;
node = malloc(sizeof *node);
if (node == NULL) {
return NULL;
}
if (*root == NULL) {
node->next = node;
} else {
node->next = (*root)->next;
(*root)->next = node;
}
node->data = data;
*root = node;
return node;
}
int dequeue(struct node **root)
{
struct node *node;
int data = 0;
node = *root;
if (node != NULL) {
node = node->next;
data = node->data;
if (*root == node) {
*root = NULL;
} else {
(*root)->next = node->next;
}
free(node);
}
return data;
}
int main(void)
{
struct node *node = NULL;
char str[512];
char *ptr;
int data;
ptr = fgets(str, sizeof str, stdin);
if (ptr != NULL) {
while (*ptr) {
data = (int)strtol(ptr, &ptr, 10);
if (!isspace(*ptr)) { // If we don't have a blank space
break; // exit the loop
}
enqueue(&node, data);
ptr++;
}
}
while (node != NULL) {
data = dequeue(&node);
printf("%d\n", data);
}
return 0;
}
输入
123 456 -789
输出
123
456
-789
推荐阅读
- java - 在接收端获取 API 发送方的 IP 地址
- java - NullPointerException 从 FXML 加载场景图,与 Spring 集成
- react-native - React-Native 和 Mapsforge
- android - 使用 Cordova 为本地静态网站提供服务?
- c++ - 匹配特殊字符的字符串
- python - 无法在 Ubuntu 18.04 上安装 Python-Rocksdb
- java - 如何在属性中使用 Lombok 定义 JSON:@JsonPropertyOrder 和 @JsonIgnore (JAVA)
- android - VoIP通话结束后如何防止最小化的应用程序留在前台?
- javascript - 如何根据 javascript 中定义的语言环境验证数字格式
- java - Liferay 7.1 - 如何为 pdf 文件添加链接 html