Given a user input of unknown length (consisting of words with maximum length 100). Is there a way to read it dynamically string by string?
It is my understanding that scanf reads a string until a space is reached, so I tried using scanf but it enters an infinite loop.
char buf[101];
while (scanf("%s", buf))
{
//something is done with the string
}
Given a user input of unknown length (consisting of words with maximum length 100) is there a way to read it dynamically string by string?
Building your own function, instead of scanf
would help to achieve this
Here, I've created a function scan
which would dynamically take in the string by increasing it's size over each iteration
I've use the additional header files string.h
and stdlib.h
for the following reasons :
functions in stdlib.h (click to know more) library file are useful for dynamic allocation of memory.
functions in string.h (click to know more) library file are useful to handle strings.
Note: the input from the user stops when he enters the string
end
.
#include <stdio.h> //the standard library file
#include <stdlib.h> //library file useful for dynamic allocation of memory
#include <string.h> //library file with functions useful to handle strings
//the function
char* scan(char *string)
{
int c; //as getchar() returns `int`
string = malloc(sizeof(char)); //allocating memory
string[0]='\0';
for(int i=0; i<100 && (c=getchar())!='\n' && c != EOF ; i++)
{
string = realloc(string, (i+2)*sizeof(char)); //reallocating memory
string[i] = (char) c; //type casting `int` to `char`
string[i+1] = '\0'; //inserting null character at the end
}
return string;
}
int main(void)
{
char *buf; //pointer to hold base address of string
while( strcmp((buf=scan(buf)),"end") ) //this loop will continue till you enter `end`
{
//do something with the string
free(buf); //don't forget to free the buf at the end of each iteration
}
free(buf); //freeing `buf` for last input i.e, `end`
}
let's just
//do something with the string
to see whether the above code works or not :)
I change the following while loop in main function :
while( strcmp((buf=scan(buf)),"end") )
{
//do something with the string
}
to
while( strcmp((buf=scan(buf)),"end") )
{
printf("you entered : %s\n",buf);
printf("size : %u\n",strlen(buf));
printf("reversing : %s\n",strrev(buf));
printf("\n-------------------\n");
free(buf);
}
and now,
input :
hall
of
fame
stay in it
end
output :
you entered : hall
size : 4
reversing : llah
-------------------
you entered : of
size : 2
reversing : fo
-------------------
you entered : fame
size : 4
reversing : emaf
-------------------
you entered : stay in it
size : 10
reversing : ti ni yats
-------------------
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With