-
arrays, pleases help!!!
i am trying to open a .txt file into an array and then print it on the screen.
i managed to do it in c++ but have been told i have to do it in c.
i think i have managed to load the file but cant display it.
it probablly quite easy but ive been pulling my hair out over it for days.
if anyone knows how to do this please let me no.
-
What are the contents of the text file?
-
It is just A-Z with no spaces
-
-
ok what u need to is to read each char by char and copy them on to the char array. And then print them all.
Have a look at function fgetc and printf
With those two function u will be able to finish of the job.
ssharish2005
-
the simplest way i can think of to do that would probably be:
Code:
FILE *fp;
char string[26]
int i;
fp = fopen("filename","r");
fscanf(fp,"%s",string);
for(i=0;i<26;i++)
printf("%c ",string[i]);
fclose(fp);
-
great, ill have a flick through an let you no how i get on, thankyou guys
-
Check if fp is NULL before you mess with it, though.
-
Code:
for(i=0;i<26;i++)
printf("%c ",string[i]);
You could have replaced this with just
Code:
printf("%s",string);
ssharish2005
-
ah, cool, ive managed to do this
Code:
#include <stdio.h>
int main ()
{
FILE *file = fopen( "key.txt", "r" );
if ( file == 0 )
{
printf( "Could not open file\n" );
}
else
{
int x;
while ( ( x = fgetc( file ) ) != EOF )
{
printf( "%c", x );
}
}
printf("\n");
if
fclose( file );
}
im trying also now to put the loaded txt file into n array, an then take a user input an swap the A's for D's (just an example), i wana make a SSC.
I was thing i hav to load it in to an array an then make if statements. If you could show me how you put the txt from the file into an array then i should be ok, i think, lol
-
It looks you literaly copied the code, but never understood what it does. When u read the char from a file that is
place the read char on to
That will store the value on to array
ssharish2005
-
should i declare the a[i] as a variable. im just starting to learn, dident realise how dificult this can be, lol.