Click here to Skip to main content
15,915,328 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do I filter my file for perfect squares

What I have tried:

C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 1024

int main(){
    char buffer[BUFFER_SIZE] = {0};
    fgets(buffer, BUFFER_SIZE, stdin);
    int     length = strlen(buffer);
    if(buffer[length-1] == '\n' ){
        buffer[length-1] = 0;
    }

    FILE *fp = fopen("buffer", "r");
    if(fp == NULL){
        printf("File not found\n");
        return 1;
    }
    int c = 0;
    while(fgets(buffer, BUFFER_SIZE, fp) >= 48 && <= 57 ){

        printf("%c", c);
    }

    fclose(fp);

    return 0;
}
Posted
Updated 2-Dec-20 20:12pm
v2

1 solution

C
int c = 0;
while(fgets(buffer, BUFFER_SIZE, fp) >= 48 && <= 57 ){
   printf("%c", c);
}

1) fgets returns a pointer to the buffer. It is highly unlikely that the address of the buffer will be between 48 and 57
2) The code && <= 57 is not valid C. Every comparison operator requires a left side and a right side. C does not string operators together like that.
3) What are the magic numbers 48 and 57? if you mean '0' and '9' use them, it will make it easier to understand when you review the code later on.
4) You never assign anything to int c, so this will always output a 0.

You probably want to look at the function atoi(), which will convert ascii strings to integers. Then you'll probably want to write a function that determines if an integer is a perfect square or not. For that, you might need to look at the sqrt() function.
For bonus points, you might want to think what you should do if the input line is something like "41Z3Q".
 
Share this answer
 
Comments
Somil Ajmera 2-Dec-20 23:01pm    
Thank you !
CPallini 3-Dec-20 2:12am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900