1. Engineering
  2. Computer Science
  3. instructions programming in c modify the code below so that...

Question: instructions programming in c modify the code below so that...

Question details

INSTRUCTIONS: Programming in C,

Modify the code below so that it converts the input string into a number, and prints the number. Write the code to convert from binary to decimal yourself (don’t use a library call). The code should respond to empty input with value 0, and should respond to invalid input with message ‘input must contain only zeros and ones’, and exit with value 1, indicating an error. Your code should be able to handle inputs of at least 20 binary digits.

****************************************************************************************************************************************************************

Some examples of how your program should work:

$ ./bindec

> 1001

9

$ ./bindec

> 11111111

255

$ ./bindec

> hello

input must contain only zeros and ones

$ ./bindec

> (no input given, just hit ‘enter’)

0

****************************************************************************************************************************************************************

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

// max length input string
#define MAXSTR 25

// convert input binary string to a number

int main() {

// user input string
char s[MAXSTR+3];

// prompt for input
printf("> ");

// read input string; at most MAXSTR+1 chars accepted
// Note: this is tricky. If we accept only MAXSTR chars,
// we can't see if user entered more chars and they are
// being dropped by fgets.
fgets(s, MAXSTR+3, stdin);

// check input length; n does not include final carriage return
int n = strlen(s)-1;
if (n > MAXSTR) {
printf("input cannot be more than %d characters\n", MAXSTR);
exit(1);
}

// convert s from a string in binary, to an int, and output

// YOUR CODE HERE

}

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution