2017-01-24 47 views
0

我遇到了以下问题。C中的文件处理和函数

我有一个程序,它允许用户创建一个.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值?
+1

[why?while(!feof(fp))'wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) – Barmar

+1

你不需要阵列。使用一个变量来保存当前的最小值。将字符串转换为数字后,检查它是否小于变量。如果是,则将新值写入变量。 – Barmar

+0

您可以在从文件中读取的循环中执行此操作,不需要先将它们放入数组中,除非您有其他原因需要所有输入。 – Barmar

回答

1

正如Barmar所提到的,没有必要将所有值存储在数组中,只是为了找到最小值。让一个变量minNr存储迄今为止读取的最小数字,并让minIdx存储它的索引。无论何时在当前通道中读取的数字更小(或相等),则minNr相应地适配minNrminIdx。因此,对于任何两个相同的数字读入,后者将被视为最小的索引。需要注意的是minNrINT_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."); 

BTW:在你的代码,如果word被声明为类似char word[50],然后声明fscanf(fp, "%s", &word)应该给你至少一个编译器警告,因为多余的&

+0

谢谢@Stephan的洞察力和想法。目前还不清楚你的意思是“'minNr是用INT_MAX初始化的,因此读入的第一个数字将”击败“这个初始值” 有关这方面的一些反馈将不胜感激。 –

+1

考虑一下你初始化'minNr',比方说'100'。如果文件只包含值> 100,那么文件的最小数字将不会被检测到,但会保持为100。那么'minNr'应该设置为最大可能的数字,即'INT_MAX'好吗? –

+1

谢谢,理解。这段代码是否需要呈现'while(!feof(fp))'不必要,还是必须在'fopen'语句之后加入? –

1

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

我不知道的ASCII值是什么,但这里是你如何:

char chars[10]; //create an array of 10 characters 
int ints[10]; //create an array of 10 ints 
char strings[10][10]; //create an array of 10 9-character strings 

我是不是正确的解决发现的最小的ASCII值的问题?

也许在语义上。但是你会因为尝试存储所有元素而导致空间效率低下(你可能不需要存储它们 - 不在内存中,不在磁盘上),2)你无法对IO进行错误处理你调用的函数。另外3)你正在创建一个没有长度限制的scanf("%s",安全漏洞。

有没有其他方式没有创建另一个数组来存储ASCII值?

是的。只存储您的当前候选人的最小值。其余的可以被遗忘。