Submersed24 Submersed24 - 2 months ago 9
C Question

storing letters from text file into array

I am a little confused how to go through an array and add put each letter in the array

notes[]
. I am unsure what is incrementing the while loop to scan each character. I am trying to pass each character through to see if it is a letter, then capitalize it.

#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)
{
while((c = getc(files)) != EOF)
{
if(isalpha(c))
{
putchar(toupper(c));
if(wordcounter == 50)
{
printf("\n");
wordcounter = 0;
}
if(charcounter == 5)
{
printf(" ");
charcounter = 0;
}
wordcounter++;
charcounter++;
}
}
}
fclose(files);
system("PAUSE");
return 0;
}


I was using this a reference:
int c;

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

Answer

This this an example of how you can add each character of a file in an array, and capitalize them.

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


int     main()
{
  FILE *fp;
  int c;
  int   index = 0;
  char  data[10000];

  fp = fopen("file.txt","r");
  if (!fp) { //We can't open the file
    return EXIT_FAILURE;
  }
  while(1)
    {
      c = fgetc(fp);
      if( feof(fp) )
        {
          data[index] = 0; //Null character to specifiate the end of the string
          break ;
        }
      data[index] = toupper(c); //This line allow store a capitalize character in the array
      ++index;
    }
  fclose(fp); //Close the file
  printf("%s", data); //show the result
  return(EXIT_SUCCESS); 
}

I hope I answered your question.

sources : https://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm