我怎么知道行号何时更改?

问题描述 投票:-1回答:2

我知道我可以将单词(作为字符串)存储在具有足够空间的char数组中。

在特定示例中,我有3个字符串的数组,每个字符串5个字节。这是我从一行中提取单词的方式:

int main(void)
{
    int i;
    char **array;
    array = (char **)malloc(3 * sizeof(char *)); // allocation

    for( i = 0; i <= 2; i++ )
    {
        array[i] = (char *)malloc(5 * sizeof(char)); // allocation
    }

    /* now I store the words */
    i = 0;
    while(i <= 2)
    {
        scanf("%s", array[i]);
        i++;
    }
}

我怎么知道行号何时更改?

c string input scanf c-strings
2个回答
-1
投票
#include <stddef.h>
#include <ctype.h>
#include <stdio.h>

#define SIZEOF_ARRAY(x) (sizeof(x) / sizeof((*x)))

int peek(FILE *stream)
{
    return ungetc(fgetc(stream), stream);
}

int main()
{
    char words[3][5] = { 0 };
    size_t words_read = 0;

    for (size_t i = 0; i < SIZEOF_ARRAY(words); ++words_read, ++i) {
        if (scanf("%4s", words[i]) != 1)
            break;

        int ch;  // discard non-whitespace characters that exceeded available storage:
        while ((ch = peek(stdin)) != EOF && !isspace(ch))
            fgetc(stdin);

        // discard whitespace until a newline is encountered:
        while ((ch = peek(stdin)) != EOF && isspace(ch) && ch != '\n')
            fgetc(stdin);

        if (ch == '\n') {
            puts("NEWLINE!");
            fgetc(stdin);  // remove the newline from the stream
        }
    }

    for (size_t i = 0; i < words_read; ++i)
        printf("%2zu: \"%s\"\n", i, words[i]);
}

-1
投票

你好,我找到了一个解决方案。只是在我得到一个字符串之后,我将使用getchar()来查看它是否为'\ n.btw thnx

© www.soinside.com 2019 - 2024. All rights reserved.