I use pointers to open a .txt
file that consists of several paragraphs. I used a for loop to store the .txt
file into a char word[i]
array and then printf
it.
Everything worked well except I don't want to store white spaces and special characters. I only want to store alphabetical characters such as ABCD......Z into my char word[i]
array.
I know I have to put if
functions into my for loops, but I don't know the exact syntax. Please help.
here is the for loop of my code :
for (i=0; i<1730; i++ )
{
fscanf(fptr,"%c", &word[i]);
printf("%c", word[i]);
};
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fptr;
char chr;
char *file_name="IdentifiedParts.txt";
fptr = fopen(file_name, "r");
while ( (fscanf(fptr,"%c",&chr)) != EOF ) {
//ASCII values : 65-90 => A-Z , 97-122 => a-z
if( (chr >= 97 && chr <= 122 ) || (chr >= 65 && chr <= 90 ) ) {
printf("%c", chr);
}
}
fclose(fptr);
return 0;
}
OR
while ( (fscanf(fptr,"%c",&chr)) != EOF ) {
if(isalpha(chr)) {
printf("%c", chr);
}
}
something like this:
#include <stdio.h>
#include <ctype.h>
int main(void){
char word[1730];
FILE* fptr = fopen("input.c", "r");
int i, ch;
for (i = 0; i<1730 && (ch = fgetc(fptr)) != EOF; i++ ){
if(isalpha(ch))
printf("%c", word[i]=ch);
}
fclose(fptr);
return 0;
}
#include <stdio.h>
int main(void){
char word[1730];
FILE* fptr = fopen("input.txt", "r");
while(!feof(fptr)){
while(1 == fscanf(fptr, "%1729[A-Za-z]", word)){
printf("%s", word);
}
fscanf(fptr, "%*[^A-Za-z]");
}
fclose(fptr);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.