h101 h101 - 2 months ago 9
C Question

how to use strtok to print a binary number?

So im trying to get a binary number from using the strtok function to iterate through a user inputted string. If the user inputs alpha it prints a 0 and if the user inputs beta it will output a 1.So if a user types in "alpha beta alpha beta alpha" the output should be "01010". I have the following code but im not sure where im going wrong as it is not doing the behavior i described

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
int main(int argc, char * argv[])
{
char userinput[250];
long binaryarray[250];
char *token;
int counter = 0;
long binarynumber =0 ;
printf("enter alpha or beta");
scanf("%s",userinput);
token = strtok(userinput, " ");
while ( token != NULL)
{
if(!strcmp(token,"alpha"))
{
binaryarray[counter] = 0;
counter +=1;
}
if(!strcmp(token,"beta"))
{
binaryarray[counter] = 1;
counter +=1;
}
token = strtok(NULL, " \0");
}
for(int i=0 ; i< counter; i++)
{
binarynumber = 10* binarynumber + binaryarray[i];
}
printf("%ld",binarynumber);
}


How would I fix this issue?

Answer

The problem is, for

  scanf("%s",userinput);

the scanning stops after encountering the first whitespace. So, it cannot scan and store an input like

alpha beta alpha beta alpha

separated by whitespace. Quoting C11, chapter ยง7.21.6.2

s

Matches a sequence of non-white-space characters.

Possible Solution: You need to use fgets() to read the user input with whitespaces.

Comments