Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Quote:
Each of these very short programs has something wrong with it. Explain what, and explain how to fix it. Your answers should each be two sentences or less.Hint: atof() and atoi() work and are not the problem


1.
#include <math.h>
#include <stdio.h>
#include <string.h>

int main(void) {
     char *s[80];
     int i;

     printf("Enter a number: ");
     fgets(s, 80, stdin);
     i = atoi(s);
     printf("You said %d.\n", i);
     return 0;
}



2.
#include <math.h>
#include <stdio.h>
#include <string.h>

int main(void) {
      int i;

     scanf("%d", i);
     printf("You said %d.\n", i);
     return 0;
}



3.
#include <math.h>
#include <stdio.h>
#include <string.h>

int main(void) {
     float x;

     scanf("%d", &x);
     printf("You said %d.\n", x);
     return 0;
}



4.
#include <math.h>
#include <stdio.h>
#include <string.h>
int main(void) {
     char s[80];
     float x, y;
     FILE *ofp;
     printf("Enter a number to square: ");
     fgets(s, 80, stdin);
     x = atof(s);
     y = x * x;

     ofp = fopen("math-results.txt", "w");
     fprintf(ofp, "%f squared is %f.\n", x, y);
     return 0;
}


What I have tried:

I am a novice beginning to learn so go easy on me - with the comments in the program you can see what I am attempting to do. I am not sure where to go from here.
Posted
Updated 9-Apr-21 14:45pm
Comments
jeron1 9-Apr-21 19:13pm    
Where to go from here is to analyze each line of each program (start with #1) and see if you can't find the issue. Surely you have a book or some class notes you can use.
[no name] 9-Apr-21 20:41pm    
It seems if you compare all 4 programs at the same time, you get an idea of what's wrong. There are differences where you might expect none. You can then research that difference.

1 solution

I'll give you hint on the first one. I'll show you the parts that are wrong but I won't tell you why.
C++
#include <math.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
     char *s[80];            <--------------------------
     int i;

     printf("Enter a number: ");
     fgets(s, 80, stdin);    <--------------------------
     i = atoi(s);            <--------------------------
     printf("You said %d.\n", i);
     return 0;
}
Look at the documentation for fgets. I'll help you with that too : fgets - C++ Reference[^]. From there, it's up to you to figure out what the error is and describe it. Another hint - the last two aren't the actual error. They are effectively errors because of the first one.

This is what you need to do with the rest of them too. They involve similar errors. Except for the last one - it's a bit more subtle.
 
Share this answer
 

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