首页 > 解决方案 > 我需要能够从标准输入中读取字符串

问题描述

我正在尝试从标准输入读取一些数据。它将是由空格分隔的数字(任何数字)。问题是我事先不知道长度。我希望能够从标准输入读取并使用它来操作某些东西,这会重复直到按下 ^d。

#include <stdio.h>
#include <stdlib.h>

int 
main(){

char input[] = scanf("%s", &input);

for(int i=0; i<sizeof(&input);i++){

//Do something

}

}

这不起作用,但我怎样才能改变它以使其工作?

标签: cscanf

解决方案


这里的主要问题是你事先不知道元素的数量,在这种情况下你需要预留空间来使用动态内存来存储元素,你可以使用队列或者你可以使用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

推荐阅读