gpt4 book ai didi

c - 将文本文件中的字母存储到数组中

转载 作者:行者123 更新时间:2023-11-30 16:56:47 25 4
gpt4 key购买 nike

我有点困惑如何遍历数组并将每个字母添加到数组 notes[] 中。我不确定是什么增加了 while 循环来扫描每个字符。我试图传递每个字符以查看它是否是字母,然后将其大写。

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

int main(){
FILE * files;
char notes[1000];
int charcounter = 0, wordcounter = 0, c;
files = fopen("input.txt", "r");
if(!files)
{
return EXIT_FAILURE;
}
if(files)
{
while(fgets(notes, sizeof notes, files) != NULL)
{
size_t i, n = strlen(notes);

for (i = 0; i < n; i++)
{
if(isalpha(notes[i]))
{
int c = toupper(notes[i]);
putchar(c);
if(wordcounter == 50)
{
printf("\n");
wordcounter = 0;
}

if(charcounter == 5)
{
printf(" ");
charcounter = 0;
}
wordcounter++;
charcounter++;
}

}
}
}
fclose(files);
system("PAUSE");
return 0;
}

我用这个作为引用:int c;

FILE *file;
file = fopen("test.txt", "r");
if (file) {
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
}

最佳答案

fgets() 将文件中的字符串读取到字符数组中。在代码中,您将一个字符串读入名为 notes 的数组中。您应该迭代该变量中的每个字符,该变量是一个 C 字符串。

一些一般性评论:a) 不要返回-1。如果您希望代码符合 ANSI C 标准,则返回 EXIT_SUCCESS 或 EXIT_FAILURE,或者对于 POSIX 平台返回正数。

b) 在调用 fgets() 时使用 sizeof,而不是对数组长度进行两次硬编码。

c) isalpha()、toupper() 和 putchar() 需要一个 int 作为参数。您的代码使用 char[1000] 数组作为参数。如果没有警告/错误,这应该不会编译。 (我尝试过,并收到警告,正如预期的那样)。始终在启用所有警告的情况下进行编译是一个好习惯,它可以避免小错误。如果您使用 gcc,选项 -Wall -Wextra -pedantic 可能很有用,至少在调试之前是这样。

这是您的程序的精简版本,以说明我的评论:

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

int main(void)
{
FILE *f;
char notes[1000];

f = fopen("input.txt", "r");
if (!f) {
return 1;
}
while (fgets(notes, sizeof notes, f) != NULL) {
size_t i, n = strlen(notes);
for (i = 0; i < n; i++) {
int c = toupper(notes[i]);
putchar(c);
}
}

fclose(f);
return 0;
}

HTH

关于c - 将文本文件中的字母存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39810634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com