how to use strtok to print a binary number? - c

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?

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.

As already said by #SouravGhosh you should use fgets to store the whole string inserted by user with white spaces.
#include <stdio.h>
#include <string.h>
int main(int argc, char * argv[])
{
char userinput[250] = {0};
char binaryarray[250];
char* token;
size_t counter = 0;
printf("enter alpha or beta");
fgets(userinput, sizeof(userinput), stdin);
token = strtok(userinput, " \n\0");
while (( token != NULL) && (count < sizeof(binaryarray)))
{
if(!strcmp(token,"alpha"))
{
binaryarray[counter] = '0';
counter++;
}
else if(!strcmp(token,"beta"))
{
binaryarray[counter] = '1';
counter++;
}
token = strtok(NULL, " \n\0");
}
for(size_t i=0 ; i< counter; i++)
{
printf("%c", binaryarray[i]);
}
printf("\n");
}
But you have other problems:
Your tokens should be " \n\0" to match all possible chars between words.
All tokens must be checked with the first strok in case of a single input, so no whitespaces
Using an int to calculate your "binary" and print it with "%ld" format specifier does not print leading zeros. You can directly store chars into the buffer.

Related

find palindromes in the row and display them

A string consisting of words, no longer than 100 characters, is supplied. Words consist of Latin characters and are separated by a single space. It is necessary to output to the standard output stream a string containing only the words palindromes.
The source data must be read into memory as a whole and all manipulations must be carried out in memory, the result obtained in memory and then printed.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int check(char str[])
{
int i, length;
length = strlen(str);
for (i = 0; i < length; i++)
if (str[i] != str[(length - 1) - i]) return 0;
return 1;
}
int main(void)
{
char str[100];
char* t;
gets(str);
t = strtok(str, " ");
while (t != NULL) {
if (check(t) == 1) {
printf("%s ", t);
}
t = strtok(NULL, " ");
}
_getch();
return 0;
}
this is my code (it fails the tests)
Please help me fix the code
Instead of fgets use function getline(&buffer, &size, stdion) for example.
Your for loop in the check function works fine but resolve another problem, than that you expected.
Palindrome a word or group of words that is the same when you read it forwards from the beginning or backwards from the end.

C Programming: Counting word length occurences in a string

How would you be able to count word lengths and output their occurrences from a string using gets() or fgets()? For example, here is code doing so but using getchar()below. I think writing it in gets() would make it easier to incorporate all of the delimiters in the program rather than having to manually set if statements for each one of those would it not?
#include <string.h>
#include <ctype.h>
const char delim[] = ", . - !*()&^%$##<> ? []{}\\ / \"";
#define SIZE 100
int main(void){
int length[SIZE] = { 0 };
int name[SIZE];
int i = 0, ch, word_len = 0;
int count = 0;
printf("enter sentence: ");
while (1){
ch = getchar();
if (isalpha(ch)){
++word_len;
}
else if (ch == ' ' || ch == '.'){
if (word_len)
length[word_len - 1]++;//-1: to 0 origin
if (ch == '.')
break;
word_len = 0;
}
}
printf("Word Length \tCount \n");
for (i = 0; i<sizeof(length) / sizeof(*length); ++i){
if (length[i])
printf(" %d \t\t%d\n", i + 1, length[i]);
}
return 0;
}
You can build your custom delimiter detection function.
// globals
const char *delim = " .,;:!?\n\0";
const int n_delim = 9;
int is_delim(int c)
{
register int i;
for (i = 0; i < n_delim; i++)
if (c == delim[i]) return 1;
return 0;
}
This function will return 1 every time it can match c with delim. So you can use it like this:
fgets(buffer, 200, stdin);
for (i = 0; i < strlen(buffer); i++) {
if (is_delim(buffer[i])) {
wl[words++] = length;
length = 0;
continue;
}
length++;
}
I'm assuming you're familiar with the fgets function.
You basically will loop through your buffer, making comparisons with each character. Every loop iteration you check if the current character is a word delimiter, if it is, you save the current length and set length=0 for a new word, and at every iteration you increment the length.
You'll need to come up with a way of either not inserting the zero length values due to double delimiters or just ignore them when you're printing the results.
Basically you want to split a string into words, based on some delimiters, and compute their length. The C standard library provides the strtok function, which does exactly what you need: it splits the given string into multiple tokens.

Word length frequency in C Program

I am trying to write a simple C program to output the length of words and output their frequencies. For example, if the user inputs "hey" my program would output Length of word: 3 Occurrences 1, and so on with a larger string inputted. I just cannot seem to loop it properly. I thought of setting both counters when a delimiter is seen to count both the length of the word at the time and its occurrence but I have not found a way for it to work. How can I fix my loop? My code is below. I'd appreciate any help. I should include my program only runs correctly for one word inputted but not a whole sentence or multiple sentences.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
const char delim[] = ", . - !*()&^%$##<> ? []{}\\ / \"";
const int n_delim = 31;
#define SIZE 1000
int is_delim(int c);
int main(){
char string[SIZE];
int wordlength = 0, wl[SIZE];
int word = 0, i;
printf("Enter your input string:");
fgets(string, SIZE, stdin);
string[strlen(string) - 1] = '\0';
printf("Word Length\tCount\n");
int seen = 0;
int l;
for (i = 0; i < strlen(string); i++){
if (is_delim(string[i])){
wl[word++] = wordlength;
l = wordlength;
seen++;
printf("%d\t\t%d\n", l, seen);
wordlength = 0;
}
wordlength++;
}
return 0;
}
int is_delim(int c){
register int i;
for (i = 0; i < n_delim; i++)
if (c == delim[i]) return 1;
return 0;
}
The trick is that wl[n] holds the count of words
of length n. Also, you don't need to keep calling strlen()
on every iteration, just check for the zero byte at the end.
The optimizer will do this for you, if you enable it.
The odd-looking for(;1;) is so that the loop counts
the final word, which is terminated by the zero byte.
memset(wl,0,sizeof(wl));
for(wordStart=maxLength=i=0;1;i++) {
if(is_delim(string[i]) || string[i]==0) {
int wordLength= i-wordStart;
if(wordLength>0)
wl[wordLength]++;
if(wordLength>maxLength)
maxLength= wordLength;
wordStart= i+1;
}
if(string[i]==0)
break;
}
for(i=1;i<=maxLength;i++) {
if(wl[i]>0) {
printf("%d words of length %d.\n",wl[i],i);
}
}
You really should use strtok for this. Right now, you never compare the last string with the current one so you can't tell them apart. You can use strcmp for this. Finally instead of manually testing the length of the string you should use strlen. Here is how your loop could look like
int seen = 0;
pch = strtok(string, delim);
last = pch;
while(pch != NULL) {
if(strcmp(last, pch) != 0) {
printf("%s:\t%d\t\t%d\n", last, (int)strlen(last), seen);
seen = 1;
}else {
seen++;
}
last = pch;
pch = strtok(NULL, delim);
}
printf("%s:\t%d\t\t%d\n", last, (int)strlen(last), seen);
Note, you should set the variable seen to 0 before the loop.

Odd behavior when converting strings to integers in C

Was working on a program taking a mathematical expression as a string and then evaluating it and discovered an odd behavior. Given
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
int ary[4];
char * string = "123+11";
for (int i = 0; i < 3; i++){
ary[i] = atoi(&string[i]);
printf("%d\n", ary[i]);
}
}
I get the output:
123
23
3
Whereas I might have expected I get the output:
1
2
3
Is this part of the atoi() function?
This is correct behavior because atoi takes a pointer to char as input and convert it into int till it finds "\0" character.
char * string = "123";
"\0" in string is present after 123.
For statement:
ary[0] = atoi(&string[0]);
atoi starts with 1 convert it to int till 123.
For statement:
ary[1] = atoi(&string[1]);
atoi starts with 2 convert it to int till 23.
For statement:
ary[2] = atoi(&string[2]);
atoi starts with 3 convert it to int till 3.
Please let me know if it is not clear.
The answer given by user3758647 is correct. To solve you problem you can use strtok function which tokenizes the input string based on delimiter.
char* string = "123+23+22";
char *token = strtok(string, "+");
int arr[4], i = 0;
arr[i] = atoi(token); //Collect first number here
while (token != NULL)
{
token = strtok(NULL, " ");
//You can collect rest of the numbers using atoi function from here
i++;
arr[i] = atoi(token);
//Do whatever you want to do with this number here.
}
return 0;

Program not registering my input correctly

#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//function prototypes
void checkAnswer(char *, char[]);
int main(void) {
char *strGame[5] = { "ADELANGUAGEFERVZOPIBMOU", "ZBPOINTERSKLMLOOPMNOCOT",
"PODSTRINGGDIWHIEEICERLS", "YVCPROGRAMMERWQKNULTHMD",
"UKUNIXFIMWXIZEQZINPUTEX" };
char answer[80] = { 0 };
int displayed = 0;
int x;
int startTime = 0;
system("clear");
printf("\n\n\tWord Find\n\n");
startTime = time(NULL);
for (x = 0; x < 5; x++) {
/* DISPLAY TEXT FOR A FEW SECONDS */
while (startTime + 3 > time(NULL)) {
if (displayed == 0) {
printf("\nFind a word in: \n\n");
printf("%s\n\n", strGame[x]);
displayed = 1;
}
}
system("clear");
printf("\nEnter word found: ");
fgets(answer, 80, stdin);
checkAnswer(strGame[x], answer);
displayed = 0;
startTime = time(NULL);
}
}
void checkAnswer(char *string1, char string2[]) {
int x;
for (x = 0; x <= strlen(string2); x++)
string2[x] = toupper(string2[x]);
if (strstr(string1, string2) != 0)
printf("\nGreat job!\n");
else
printf("\nSorry, word not found!\n");
}
When I run the code, it doesn't register my input correctly. It tells me that the word wasn't found. I used toupper to make my input the same as my strings and strstr to compare my input with the strings. I took this from a basic C programming book. It used gets. I know that you shouldn't use gets so I changed it to fgets. Is this where the problem is? Any suggestions?
You can avoid the issue with the \n (newline) mentioned by BLUEPIXY -- namely, that gets() removes it but fgets() does not -- by reversing the terms in your call to checkAnswer():
checkAnswer(answer, strGame[x]);
checkAnswer() then uses the same order with strstr(). If you search for "foobar" in "foobar\n", strstr() will return a pointer. But if you search for "foobar\n" in "foobar", it won't.
The newline is there because the user hits Enter. So another way around this would be to add a \n to the end of all your strGame[] strings. Or, you could remove any newline in the answer with:
void truncateAtNewline (char *str) {
char *p = strchr(str, '\n');
if (p) *p = '\0';
}
The problem is that fgets() will leave the newline at the end of the string. When you type the word, then you press Enter and fgets() interprets that as input.
So, a way to bypass this is to eat the newline by doing this:
fgets(answer, 80, stdin);
// go to the last position where the
// newline is placed and replace it
// with the null terminator
answer[strlen(answer)-1] = '\0';
Also here:
for (x = 0; x <= strlen(string2); x++)
string2[x] = toupper(string2[x]);
the <= is not needed, since you start from 0, thus change it to this:
for (x = 0; x < strlen(string2); x++)
string2[x] = toupper(string2[x]);
How I found your problem? I used printf to output the strings before comparing them.
void checkAnswer(char *string1, char string2[]) {
int x;
for (x = 0; x < strlen(string2); x++)
string2[x] = toupper(string2[x]);
printf("|%s|\n", string1);
printf("|%s|\n", string2);
if (strstr(string1, string2) != 0)
printf("\nGreat job!\n");
else
printf("\nSorry, word not found!\n");
}
Output before my fix:
|ADELANGUAGEFERVZOPIBMOU|
|ADEL
|
Output after the fix:
|ADELANGUAGEFERVZOPIBMOU|
|ADEL|
Or you can use a function to trim newlines and spaces. I have some methods here.
Consider also not using system().
Moreover, always add a return 0; line of code before your main() ends.

Resources