我正在尝试编写一个程序,其中有一个整数,名为 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
的适当数量的单词时使我的程序正常工作?预先感谢您。
最佳答案
修改后的示例:如果满足字数配额或读取 EOF,则中断 while
循环。
我任意选择了 5 作为 words_expected
(而不是原始代码中的 numwords
)。一旦读取了五行输入,就会打印结果。不需要显式的 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
可能是明智之举。
关于c - 从 stdin 读取输入到指针数组中直到 EOF,但没有任何输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56764329/