0

I am doing a basic c programming problem online online. Basically what I have to do is take in an input(from the console), say

00000100+10000001

and produce the right output

00000011

I found an algorithm that i could use to convert binary to decimal and decimal to binary. I don't need help on that part. The problem states that you shouldn't use arrays(strings included). What I was thinking was to take user input of one digit at a time and then process each digit. However whenever I use the

scanf("%d",&i)

, input always advances to a new line which i want to avoid in order for the input and output to match up. Does anyone know how how to take in one digit from the user without moving to the next line?

committedandroider
  • 8,711
  • 14
  • 71
  • 126

2 Answers2

1

If I'm understanding the problem correctly, arrays (and thus strings as character arrays) are banned, but character I/O in general probably isn't? If that's the case, you can read in and process one character at a time using getc().

1

Limit the width of the scan.

if (scanf("%1d",&i) != 1) 
  Handle_Failure();  // This is likely the '+' in stdin.

Remember that stdin is typically line buffered. No input, into scanf(), getc(), etc. is seen until the user completes the line.


Recommend instead to read the user's line of input and process the buffer. Process 1 char at a time if desired.

char buf[1000];
if (fgets(buf, sizeof buf, stdin) == NULL) Handle_IOError_or_EOF();

char *s = buf;
while (*s) {
  Parse_Buffer();
  s++;
}
Do_Stuff();
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256