Zac*_*ene 7 c arrays string character-arrays output
我正在为学校编写一个程序,要求从文件中读取文本,将所有内容都大写,并删除标点符号和空格.文件"Congress.txt"包含
(国会不得制定任何法律,尊重宗教信仰,禁止自由行使;或者剥夺言论自由或新闻自由;或者人民和平集会的权利,并向政府请求补救不满.)
它读入正确,但我到目前为止删除标点,空格和大写导致垃圾字符的一些主要问题.到目前为止我的代码是:
void processFile(char line[]) {
FILE *fp;
int i = 0;
char c;
if (!(fp = fopen("congress.txt", "r"))) {
printf("File could not be opened for input.\n");
exit(1);
}
line[i] = '\0';
fseek(fp, 0, SEEK_END);
fseek(fp, 0, SEEK_SET);
for (i = 0; i < MAX; ++i) {
fscanf(fp, "%c", &line[i]);
if (line[i] == ' ')
i++;
else if (ispunct((unsigned char)line[i]))
i++;
else if (islower((unsigned char)line[i])) {
line[i] = toupper((unsigned char)line[i]);
i++;
}
printf("%c", line[i]);
fprintf(csis, "%c", line[i]);
}
fclose(fp);
}
Run Code Online (Sandbox Code Playgroud)
我不知道这是否是一个问题,但我将MAX定义为272,因为这是文本文件包括标点符号和空格.
我得到的输出是:
C???????????????????????????????????????????????????????????????????????????????
?????????????????????????????????????????????????????????Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)
基本算法需要遵循:
while next character is not EOF
if it is alphabetic
save the upper case version of it in the string
null terminate the string
Run Code Online (Sandbox Code Playgroud)
转换为C为:
int c;
int i = 0;
while ((c = getc(fp)) != EOF)
{
if (isalpha(c))
line[i++] = toupper(c);
}
line[i] = '\0';
Run Code Online (Sandbox Code Playgroud)
此代码不需要(unsigned char)
使用函数转换,<ctype.h>
因为c
保证包含EOF(在这种情况下它不会进入循环体)或者转换为unsigned char
无论如何转换的字符的值.您只需在使用时担心演员表char c
(如在问题中的代码中)并尝试写toupper(c)
或isalpha(c)
.问题是plain char
可以是一个带符号的类型,因此一些字符,众所周知的ÿ(y-umlaut,U + 00FF,LATIN SMALL LETTER Y WITH DIAERESIS),将显示为负值,并且打破了对输入的要求该<ctype.h>
功能.此代码将尝试对已经大写的字符进行大小写转换,但这可能比第二次测试便宜.
你在打印方面做了什么等等取决于你.的csis
文件流是一个全局变量的范围; 那有点(tr)icky.您可能应该使用换行符终止输出打印.
显示的代码容易受到缓冲区溢出的影响.如果长度line
为MAX
,则可以将循环条件修改为:
while (i < MAX - 1 && (c = getc(fp)) != EOF)
Run Code Online (Sandbox Code Playgroud)
如果是更好的设计,则将函数签名更改为:
void processFile(int size, char line[]) {
Run Code Online (Sandbox Code Playgroud)
并声称尺寸严格为正:
assert(size > 0);
Run Code Online (Sandbox Code Playgroud)
然后循环条件变为:
while (i < size - 1 && (c = getc(fp)) != EOF)
Run Code Online (Sandbox Code Playgroud)
显然,你也改变了电话:
char line[4096];
processFile(sizeof(line), line);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1189 次 |
最近记录: |