Submersed24 Submersed24 - 2 months ago 9
C Question

cypher alphabet to array - capitalized and grouped

I have been trying to get this program to work for like 10 hours, I am doing something wrong and I am still unsure why the program doesn't work. Every time I look up how to do it, it is a different variation of what I am trying to do and when I try to modify it, it does not work. This program is supposed to take only letters of a text file and output them in groups of 5 letters, capitalized. What am I doing wrong here?Thanks

#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;
}

Answer

You're checking the value of the counters before you increment them. Because of this, the counter starts at 0 on the first word but then starts at 1 on each subsequent word. So on the first word you're capturing 6 letters instead of 5.

Do the increment first before the limit check. Also, check charcounter before wordcounter so you don't have an extra space at the start of the second and subsequent lines:

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

Input file:

I am trying to see whether or not this works correctly this quick brown fox
jumps over the lazy dog. Hold it now, hold it now, hold it now, HIT IT!!

Output:

IAMTR YINGT OSEEW HETHE RORNO TTHIS WORKS CORRE CTLYT HISQU 
ICKBR OWNFO XJUMP SOVER THELA ZYDOG HOLDI TNOWH OLDIT NOWHO 
LDITN OWHIT IT
Comments