从stdin读取输入到指针数组,直到EOF,但没有任何输出?

时间:2019-06-26 02:25:54

标签: c arrays scanf stdin eof

我正在尝试编写一个程序,其中有一个名为numwords的整数,该整数指定从文件中读取的单词数。但是,我正在针对单词少于用户输入的文件测试它。例如,我有输入

this

should

not 

work

,其中numwords根据用户输入为5。我想用退出代码1终止程序,所以我写了以下代码来帮助我:

当我使用具有适当数量的单词的文件作为用户输入numwords的文件时,似乎没有输出输出(程序具有使用wptrs打印值的其他功能)。在将while语句添加到我的代码之前,正在打印输出。我觉得while循环中的scanf语句出了点问题。在添加到while循环之前,我仅使用了for循环和注释掉的scanf("%s", unused),并且我的程序正常工作-正在读入输入,并使用了适当的输出。我只是想实现一种条件,在这种情况下,单词少于numwords的情况将失败。

//A huge chunk of memory that stores the null-terminated words contiguously
char chunk[MEMSIZE];

//Location of unused memory
char *unused = chunk;

//Points to words that reside inside of chunk
char *wptrs[MAX_WORDS];

/** Total number of words in the dictionary */
int numwords;

void readwords()
{
  int i = 0;
  while ((scanf("%s", unused)) != EOF) {
    for (i = 0; i < numwords; i++) {
      //Read in words and store them in chunk array
      //scanf("%s", unused);
      wptrs[i] = unused;
      unused += mystrlen(wptrs[i]) + 1;
    }
  }

  //Check to see if fewer input than specified
  if (numwords > i) {
    printf("%d", i);
    exit(EXIT_NUM_WORDS_BAD);
  }
}

我希望这种情况以退出代码1退出程序,但是我发现它以代码0退出,因为main方法只有return 0。有没有一种方法可以退出代码1,并且在有与numwords相当数量的单词时使我的程序正常工作?预先谢谢你。

1 个答案:

答案 0 :(得分:1)

修改后的示例:如果符合单词配额或读取了EOF的情况,就会跳出while循环。

我已为words_expected(而是原始代码中的numwords)选择了5。读取五行输入后,将打印结果。不需要明确的EOF。如果在5个字之前遇到EOF,则会打印错误,并返回返回码1。

根据您的评论,我添加了一项检查,以确定给定行是否仅包含数字。如果是这样,程序将停止处理输入。

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

#define MEMSIZE 1024
#define MAX_WORDS 5

//A huge chunk of memory that stores the null-terminated words contiguously
char chunk[MEMSIZE];

//Location of unused memory
char *unused = chunk;

//Points to words that reside inside of chunk
char *wptrs[MAX_WORDS];

/** Total number of words in the dictionary */
int words_expected = 5;

int contains_only_digits(char *s)
{
    int i = 0;
    for (i = 0; i < strlen(s); i++) {
        if (!isdigit(s[i])) {
            return 0;
        }
    }

    return 1;
}

void readwords()
{
    int words_read = 0;
    while (words_read < words_expected && scanf("%s", unused) != EOF) {
        // Read in words and store them in chunk array
        wptrs[words_read] = unused;
        if (contains_only_digits(wptrs[words_read])) {
            break;
        }
        unused += strlen(wptrs[words_read]) + 1;
        words_read++;
    }

    //Check to see if fewer input than specified
    if (words_read < words_expected) {
        printf("Expected %d words, but %d were provided\n", words_expected,
                words_read);
        exit(1);
    }
}

void printwords()
{
    int i = 0;
    for (i = 0; i < words_expected; i++) {
        printf("word %d: %s\n", i + 1, wptrs[i]); 
    }
}

int main(int argc, char **argv)
{
    readwords();
    printwords();
}

contains_only_digits函数是一个简单的实现。如果您对确定C字符串是否为数字的最佳实践感兴趣,可以使用strtol并检查errno

相关问题