gpt4 book ai didi

c - C 中的文件处理和函数

转载 作者:太空宇宙 更新时间:2023-11-04 08:07:24 25 4
gpt4 key购买 nike

我遇到了以下问题。

我有一个程序允许用户创建一个 .txt 文件并添加最多 10 个 ASCII 值。然后我关闭文件,并以读取模式重新打开。这一点是我使用 ATOI 将输入的 ASCII 转换为整数。

下面提供了它的工作代码。

我的问题是:我想创建某种数组来存储这些输入的 ASCII 值。通过这样做,这将使我能够调用一个函数来检查这些 ASCII 值中哪个值最小。

fp = fopen("c:\\CTEMP\\1.txt", "w+");
{
for (x = 0; x < 10; x++)
{
printf("\nType the word you want to add. Type exit to terminate: ");
scanf("%s", word); // word is declared as char word[10]

if (strcmp(word, "exit") == 0)
{
break;
}
fprintf(fp, "%s\n", word);
words++;
}
fclose(fp);
}
fp = fopen("C:\\CTEMP\\1.txt", "r");

while (!feof(fp))
{
fscanf(fp, "%s", &word);
number = atoi(word);
printf("\nstring is \t %s\n", word);
printf("integer is \t %d\n", number);

// location = find_minimum(array,number);
// minimum = array[location];

// printf("Minimum element location = %d and value = %d.\n", location + 1, minimum);
}
scanf_s("%d");
}
  1. 我是否解决了正确找到最小 ASCII 值的问题?
  2. 有没有其他方法可以不创建另一个数组来存储 ASCII 值?

最佳答案

正如 Barmar 所提到的,没有必要为了找到最小值而将所有值存储在一个数组中。让变量 minNr 存储到目前为止读取的最小数字,并让 minIdx 存储它的索引。每当当前 channel 中读取的数字小于(或等于)minNr 时,相应地调整 minNrminIdx。因此,对于读入的任意两个相等数,后者将被视为最小值的索引。请注意,minNr 是用 INT_MAX 初始化的,这样读入的第一个数字就会“击败”这个初始值:

int finished = 0;
int minNr = INT_MAX;
int minIdx = 0;

fp = fopen("C:\\CTEMP\\1.txt", "r");
if (fp==NULL)
finished=1;

for (int i=1; !finished; i++)
{
char word[50];
if (fscanf(fp, "%s", word) < 1)
finished = 1;
else {
int number = atoi(word);
printf("\nstring is \t %s\n", word);
printf("integer is \t %d\n", number);

if (number <= minNr) {
minNr = number;
minIdx = i;
}
}
}
if (minIdx > 0)
printf ("min number is %d at position %d\n", minNr, minIdx);
else
printf("no numbers read in; hence: no minimum calculated.");

顺便说一句:在您的代码中,如果 word 被声明为类似 char word[50] 的内容,则声明 fscanf(fp, "%s", &word) 应该至少给你一个编译器警告,因为多余的 &

关于c - C 中的文件处理和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41839304/

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