我正在为课程的后半部分工作,程序的目标很简单,但我无法弄清楚导致我的程序输出的原因。基本上,我们必须使用我们为字符串标题编写的函数来读取文件。然后我们应该打印出该文件中的所有四个字母的单词,显然忽略了标点符号和空格。我已经掌握了这个逻辑,但我无法弄明白的是,为什么,即使我在打印之前检查字符串的长度是否为4,我有时会得到输出&#39 ; s明显长于4.这是我使用的文件中的输入文本。
This is a test of the program which will only print out the four letter words in this file. Let's see if it works!
这就是我得到的输出......
This
test
willham
onlyham
fourtam
thissrm
filesrm
以下是主要计划:http://pastebin.com/xviETPFm
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "mystring.h"
int fTerminate(char ch, int * pbDiscardChar);
int main(int argc, char ** argv) {
MYSTRING str;
FILE * in;
if((str = mystring_init_default()) == MYSTRING_STATUS_ERROR) {
printf("Error initializing MYSTRING object.\n");
return -1;
}
if((in = fopen("book.txt", "r")) == NULL) {
printf("Error opening file \"book.txt\". Does the file exist?\n");
return -1;
}
while(mystring_input(str, in, 1, fTerminate) != MYSTRING_STATUS_ERROR) {
if(mystring_size(str) == 4) {
mystring_output(str, stdout);
printf("\n");
}
}
mystring_destroy(&str);
return 0;
}
int fTerminate(char ch, int * pbDiscardChar) {
// Terminate on whitespace characters or non-alpha characters.
return (*pbDiscardChar = ((isspace(ch) || (isalpha(ch) == 0))?1:0));
}
如果你需要它,这里是输入函数:http://pastebin.com/vD71hGEt
MyString_Status mystring_input(MYSTRING hString,
FILE * hFile,
int bIgnoreLeadingWhiteSpace,
int (*fTerminate)(char ch, int * pbDiscardChar)) {
char ch = '\0';
int eofCheck = 0;
int t, discard;
mystring_truncate(hString, 0);
if(hFile == NULL) return MYSTRING_STATUS_ERROR;
eofCheck = fscanf(hFile, "%c", &ch);
// If bIgnoreWhiteSpace is true, gobble leading whitespace.
if(bIgnoreLeadingWhiteSpace) {
while(isspace(ch)) {
eofCheck = fscanf(hFile, "%c", &ch);
if(eofCheck == EOF) return MYSTRING_STATUS_ERROR;
}
}
// Add all valid characters to the string, overwriting the old string.
while(eofCheck != EOF) {
t = fTerminate(ch, &discard);
if(discard == 0) mystring_push(hString, ch);
if(t) return MYSTRING_STATUS_SUCCESS;
eofCheck = fscanf(hFile, "%c", &ch);
}
if(eofCheck == EOF) return MYSTRING_STATUS_ERROR;
return MYSTRING_STATUS_SUCCESS;
}
它显然适用于前两个字符串,那么其余部分又发生了什么?我的电脑就像火腿一样吗?