char * removeChar(char * str, char c){
int len = strlen(str);
int i = 0;
int j = 0;
char * copy = malloc(sizeof(char) * (len + 1));
while(i < len){
if(str[i] != c){
copy[j] = str[i];
j++;
i++;
}else{
i++;
}
}
if(strcmp(copy, str) != 0){
strcpy(str,copy);
}else{
printf("Error");
}
return copy;
}
int main(int argc, char * argv[]){
char str[] = "Input string";
char * input;
input = removeChar(str,'g');
printf("%s\n", input);
free(input);
return 0;
}
I don't know why every time I try to run it ,it always says uninitialized variable and sticks in the strcpy line and printf line.
Basically this function is to take a string, and a character and removes the that character from the string (because I am learning malloc so that's why I wrote the function like this).
After the while loop do:
copy[j] = '\0';
to NULL-terminate your string; that way it can work with methods coming from <string.h>, which assume that the string is nul-terminated.
PS: One warning you should see is about not returning copy in your function in any case, because now if the condition of the if statement is wrong, your function won't return something valid, so add this:
return copy;
at the end of your function (which is now corrected with your edit).
Other than that, the only warning you should still get are for the unused arguments of main(), nothing else:
prog.c: In function 'main':
prog.c:32:14: warning: unused parameter 'argc' [-Wunused-parameter]
int main(int argc, char * argv[]){
^~~~
prog.c:32:27: warning: unused parameter 'argv' [-Wunused-parameter]
int main(int argc, char * argv[]){
^~~~
While you copy over bytes from str to copy, you don't add a terminating null byte at the end. As a result, strcmp reads past the copied characters into unitialized memory, possibly past the end of the allocated memory block. This invokes undefined behavior.
After your while loop, add a terminating null byte to copy.
Also, you never return a value if the if block at the end is false. You need to return something for that, probably the copied string.
char * removeChar(char * str, char c){
int len = strlen(str);
int i = 0;
int j = 0;
char * copy = malloc(sizeof(char) * (len + 1));
while(i < len){
if(str[i] != c){
copy[j] = str[i];
j++;
i++;
}else{
i++;
}
}
// add terminating null byte
copy[j] = '\0';
if(strcmp(copy, str) != 0){
strcpy(str,copy);
}
// always return copy
return copy;
}
You never initialised input and the some compilers don't notice,
that the the value is never used before the line
input = removeChar(str, 'g');
in your code. So they emit the diagnostic just to be sure.
strcpy(str, copy)
gets stuck in your code, as copy never got a closing 0 byte and
so depends on the nondeterministic content of your memory at the
moment of the allocation of the memory backing copy, how long strcpy
will run and if you get eventually a SIGSEGV (or similar).
strcpy will loop until it finds a 0 byte in your memory.
For starters to remove a character from a string there is no need to create dynamically a character array and then copy this array into the original string.
Either you should write a function that indeed removes the specified character from a string or a function that creates a new string based on the source string excluding the specified character.
It is just a bad design that only confuses users. That is the function is too complicated and uses redundant functions like malloc, strlen, strcmp and strcpy. And in fact it has a side effect that is not obvious. Moreover there is used incorrect type int for the length of a string instead of the type size_t.
As for your function implementation then you forgot to append the terminating zero '\0' to the string built in the dynamically allocated array.
If you indeed want to remove a character from a string then the function can look as it is shown in the demonstrative program.
#include <stdio.h>
char * remove_char(char *s, char c)
{
char *p = s;
while (*p && *p != c) ++p;
for ( char *q = p; *p++; )
{
if (*p != c) *q++ = *p;
}
return s;
}
int main( void )
{
char str[] = "Input string";
puts(str);
puts(remove_char(str, 'g'));
return 0;
}
The program output is
Input string
Input strin
If you are learning the function malloc and want to use it you in any case should try to implement a correct design.
To use malloc you could write a function that creates a new string based on the source string excluding the specified character. For example
#include <stdio.h>
#include <stdlib.h>
char * remove_copy_char(const char *s, char c)
{
size_t n = 0;
for (const char *p = s; *p; ++p)
{
if (*p != c) ++n;
}
char *result = malloc(n + 1);
if (result)
{
char *q = result;
for (; *s; ++s)
{
if (*s != c) *q++ = *s;
}
*q = '\0';
}
return result;
}
int main( void )
{
char *str = "Input string";
puts(str);
char *p = remove_copy_char(str, 'g');
if ( p ) puts(p );
free(p);
return 0;
}
The program output will be the same as above.
Input string
Input strin
Pay attention to the function declaration
char * remove_copy_char(const char *s, char c);
^^^^^^
In this case the source string can be a string literal.
char *str = "Input string";
Related
I want to write a program in C that displays each word of a whole sentence (taken as input) at a seperate line. This is what I have done so far:
void manipulate(char *buffer);
int get_words(char *buffer);
int main(){
char buff[100];
printf("sizeof %d\nstrlen %d\n", sizeof(buff), strlen(buff)); // Debugging reasons
bzero(buff, sizeof(buff));
printf("Give me the text:\n");
fgets(buff, sizeof(buff), stdin);
manipulate(buff);
return 0;
}
int get_words(char *buffer){ // Function that gets the word count, by counting the spaces.
int count;
int wordcount = 0;
char ch;
for (count = 0; count < strlen(buffer); count ++){
ch = buffer[count];
if((isblank(ch)) || (buffer[count] == '\0')){ // if the character is blank, or null byte add 1 to the wordcounter
wordcount += 1;
}
}
printf("%d\n\n", wordcount);
return wordcount;
}
void manipulate(char *buffer){
int words = get_words(buffer);
char *newbuff[words];
char *ptr;
int count = 0;
int count2 = 0;
char ch = '\n';
ptr = buffer;
bzero(newbuff, sizeof(newbuff));
for (count = 0; count < 100; count ++){
ch = buffer[count];
if (isblank(ch) || buffer[count] == '\0'){
buffer[count] = '\0';
if((newbuff[count2] = (char *)malloc(strlen(buffer))) == NULL) {
printf("MALLOC ERROR!\n");
exit(-1);
}
strcpy(newbuff[count2], ptr);
printf("\n%s\n",newbuff[count2]);
ptr = &buffer[count + 1];
count2 ++;
}
}
}
Although the output is what I want, I have really many black spaces after the final word displayed, and the malloc() returns NULL so the MALLOC ERROR! is displayed in the end.
I can understand that there is a mistake at my malloc() implementation, but I do not know what it is.
Is there another more elegant or generally better way to do it?
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
Take a look at this, and use whitespace characters as the delimiter. If you need more hints let me know.
From the website:
char * strtok ( char * str, const char * delimiters );
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.
Parameters
str
C string to truncate.
Notice that this string is modified by being broken into smaller strings (tokens).
Alternativelly [sic], a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
delimiters
C string containing the delimiter characters.
These may vary from one call to another.
Return Value
A pointer to the last token found in string.
A null pointer is returned if there are no tokens left to retrieve.
Example
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
For the fun of it here's an implementation based on the callback approach:
const char* find(const char* s,
const char* e,
int (*pred)(char))
{
while( s != e && !pred(*s) ) ++s;
return s;
}
void split_on_ws(const char* s,
const char* e,
void (*callback)(const char*, const char*))
{
const char* p = s;
while( s != e ) {
s = find(s, e, isspace);
callback(p, s);
p = s = find(s, e, isnotspace);
}
}
void handle_word(const char* s, const char* e)
{
// handle the word that starts at s and ends at e
}
int main()
{
split_on_ws(some_str, some_str + strlen(some_str), handle_word);
}
malloc(0) may (optionally) return NULL, depending on the implementation. Do you realize why you may be calling malloc(0)? Or more precisely, do you see where you are reading and writing beyond the size of your arrays?
Consider using strtok_r, as others have suggested, or something like:
void printWords(const char *string) {
// Make a local copy of the string that we can manipulate.
char * const copy = strdup(string);
char *space = copy;
// Find the next space in the string, and replace it with a newline.
while (space = strchr(space,' ')) *space = '\n';
// There are no more spaces in the string; print out our modified copy.
printf("%s\n", copy);
// Free our local copy
free(copy);
}
Something going wrong is get_words() always returning one less than the actual word count, so eventually you attempt to:
char *newbuff[words]; /* Words is one less than the actual number,
so this is declared to be too small. */
newbuff[count2] = (char *)malloc(strlen(buffer))
count2, eventually, is always one more than the number of elements you've declared for newbuff[]. Why malloc() isn't returning a valid ptr, though, I don't know.
You should be malloc'ing strlen(ptr), not strlen(buf). Also, your count2 should be limited to the number of words. When you get to the end of your string, you continue going over the zeros in your buffer and adding zero size strings to your array.
Just as an idea of a different style of string manipulation in C, here's an example which does not modify the source string, and does not use malloc. To find spaces I use the libc function strpbrk.
int print_words(const char *string, FILE *f)
{
static const char space_characters[] = " \t";
const char *next_space;
// Find the next space in the string
//
while ((next_space = strpbrk(string, space_characters)))
{
const char *p;
// If there are non-space characters between what we found
// and what we started from, print them.
//
if (next_space != string)
{
for (p=string; p<next_space; p++)
{
if(fputc(*p, f) == EOF)
{
return -1;
}
}
// Print a newline
//
if (fputc('\n', f) == EOF)
{
return -1;
}
}
// Advance next_space until we hit a non-space character
//
while (*next_space && strchr(space_characters, *next_space))
{
next_space++;
}
// Advance the string
//
string = next_space;
}
// Handle the case where there are no spaces left in the string
//
if (*string)
{
if (fprintf(f, "%s\n", string) < 0)
{
return -1;
}
}
return 0;
}
you can scan the char array looking for the token if you found it just print new line else print the char.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
int len = strlen(s);
char delim =' ';
for(int i = 0; i < len; i++) {
if(s[i] == delim) {
printf("\n");
}
else {
printf("%c", s[i]);
}
}
free(s);
return 0;
}
char arr[50];
gets(arr);
int c=0,i,l;
l=strlen(arr);
for(i=0;i<l;i++){
if(arr[i]==32){
printf("\n");
}
else
printf("%c",arr[i]);
}
i wrote this code without looking on the net and having a look in the builtin.
how can remove that temp variable and write directly in one of the variable passed in strcat12()?
#include <stdio.h>
char temp[]="";
int strlen12(char *str) {
int count = 0;
while(*str) {
count++;
str++;
}
return count;
}
char strcat12(char *str, char *str2) {
int i = 0;
int l = strlen12(str);
while(*str) {
temp[i++] = *str;
str++;
}
while(*str2) {
temp[l++] = *str2;
str2++;
}
}
The code has some errors and some place on which it can comply with standard.
strlen function returns the length of the string. Better would be if you return size_t and parameter is of type const char*.
Now strcat doesn't behave the way you implemented it. What happens then? Standard says
char *strcat(char * restrict s1, const char * restrict s2);
The strcat function appends a copy of the string pointed to by s2 (including the terminating null character) to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1. If copying takes place between objects that overlap, the behavior is undefined.
Returns
The strcat function returns the value of s1.
char * mystrcat(char *dest, const char *src)
{
size_t i=0,j=0;
while( dest[i] ) i++ ;
while( src[j] ) { dest[i+j] = src[j]; j++; }
dest[i+j] = '\0';
return dest;
}
The same way strlen() returns size_t.
size_t strlen(const char *s){
size_t len = 0;
for( ; s[len] ; len++ )
;
return len;
}
Now the problems in your code
char temp[]="" this is an one length string containing only the single character \0.
This is not a good idea to have a function that will fill one of the char array when called with 2 strings. This side effect is not desirable and it is not reusable.
char strcat12(char *str, char *str2) You are supposed to return a char but you returned nothing.
char strcat12(char *str, char *str2) Again why do you want to return a char?
Now if you are using a global variable why do you even need to return anything as far as the code is given. void strcat12(char *str, char *str2) will be ok.
A slightly better idea can be that you will return a char* which will contain the concatenated string. What I mean by this is you will allocate memory and return pointer to that memory and the memory holds concatenated string.
regarding your question: how can remove that temp variable and write directly in one of the variable passed in strcat12()?
to write directly into the parameter 'str', the array pointed to by 'str' must be long enough to hold the contents of both parameters + the terminating NUL byte.
Then the variable temp[] does not need to be referenced.
here is one way to implement the strcat12() function:
char * strcat12(char *dest, const char *src)
{
size_t i;
for (i = 0; dest[i]; i++);
for (size_t j = 0; src[j]; j++)
dest[i+j] = src[j];
dest[i+j] = '\0';
return dest;
}
I have the following simple program that reads character by character a text file. Each time a character is read from the file, must go at the end of the str which is a string. For this reason I made a small function called conc which takes the character, reallocates the str and then takes the character at the end of the string (str[count] = ch).
After the EOF character, I put the '\0' character to the str as an end for the string variable.
My question is why the last printf displays garbage?? Any ideas??
Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void conc(char* str,char ch,int* count);
int main(int argc,char** argv)
{
char* str = (char*)malloc(sizeof(char));
char ch;
int count = 0,i;
FILE* fp = fopen("path","r");
if(fp == NULL){
printf("No File Found");
return 1;
}
ch=fgetc(fp);
while(ch!=EOF){
conc(str,ch,&count);
ch=fgetc(fp);
}
str[count] = '\0';
printf("%s",str);
free(str);
return(0);
}
void conc(char* str,char ch,int* count){
str[*count] = ch;
(*count)++;
//printf("\n%c",str[(*count)-1]);
str = (char*)realloc(str,(*count)+1);
}
The problem is with how you realloc() the pointer. The changes you do to str will not modify the original pointer in main(). You are only assigning to the copy of the pointer str in conc(). You need to pass a pointer to pointer in order to modify it.
void conc(char** str,char ch,int* count){
(*str)[*count] = ch;
(*count)++;
*str = realloc(*str,(*count)+1);
}
and pass a pointer to it from main():
conc(&str,ch,&count);
Change the prototype to match:
void conc(char** str,char ch,int* count);
Others notes:
1) when realloc() fails it returns NULL and you will lose the original pointer. So you need to use a temporary and assign to the original.
See: Having dynamically allocated an array can I change its size?
2) Casting malloc()/realloc() etc is also dangerous.
3) Always check the return value of malloc() etc to see if the memory allocation failed.
3) Allocating one char at a time is not very efficient. Typical way is to allocate a buffer of size N and double the size when you realloc().
It is not necessary to pass count to your function because you are (or rather, should be) passing it a proper zero terminated string, and the new character should always be added to its end.
If you are going to modify str anyway, it's slightly better to start out with str = NULL. On its first call, set str to occupy 2 bytes to begin with, and add 1 character each next call.
Be careful with char ch; and then using while(ch!=EOF) ..! This will only work when your default char is signed. It will also prematurely stop when you encounter a byte 0FFh in your input.
With these points in mind, I end up with this:
char *conc (char *str, char ch);
int main (void)
{
char *str = NULL;
int ch;
FILE* fp = fopen("path","r");
if(fp == NULL){
printf("No File Found");
return 1;
}
ch=fgetc(fp);
while(ch!=EOF)
{
str = conc (str, ch);
ch = fgetc(fp);
}
printf("%s",str);
free(str);
return 0;
}
char *conc (char *str, char ch)
{
int last_pos;
if (str)
{
last_pos = strlen(str);
str = realloc (str, last_pos+1);
} else
{
str = malloc(2);
last_pos = 0;
}
str[last_pos] = ch;
str[last_pos+1] = 0;
return str;
}
All I want to ask a question that if we have two string but these should be in the given code
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
char *getln()
{
char *line = NULL, *tmp = NULL;
size_t size = 0, index = 0;
int ch = EOF;
while (ch) {
ch = getc(stdin);
if (ch == EOF || ch == '\n')
ch = 0;
if (size <= index) {
size += index;
tmp = realloc(line, size);
if (!tmp) {
free(line);
line = NULL;
break;
}
line = tmp;
}
line[index++] = ch;
}
return line;
}
char * combine(char *a,char *buffer){
int stop_var;
int newSize = strlen(a) + strlen(buffer) + 1;
char * newBuffer = (char *)malloc(newSize);
strcpy(newBuffer,a);
strcat(newBuffer,buffer); // or strncat
//printf("Final String %s",newBuffer);
free(a);
a = newBuffer;
return newBuffer;
}
char * fun(char *str)
{
char *str1;
str1=getln();
str=combine(str,str1);
return str;
}
int main(void)
{
char *str;
str= getln();
printf("Initial String %s \n",str);
str=fun(str);
printf("Final String %s \n",str);
}
this code is working fine but string char *str="Fixed value" is fixed is gives runtime error
int main(void)
{
char *str;
str= "Fixed Value";
printf("Initial String %s \n",str);
str=fun(str);
printf("Final String %s \n",str);
}
So, I want to know is it any other way to run the above case in which the string is fixed. I know that "How can we achieve the final value in the same character pointer".
Please Read Note:
There are many Questions related to this question I have tried all the solutions.
I looked the below solutions
concatenate-two-char-arrays-into-single-char-array-using-pointers
concatenate-two-char-arrays
how-to-concatenate-pointer-arrays
concatenate-char-array-in-c
concatenate-two-arrays-using-void-pointer-c
I have searched many more solutions over the internet, but no solutions are fulfilled my condition. These all the solution is using the third variable and showing its value. I want value in the same variable. Even if we are creating any extra variable, its value finally should be assign to char *str.
Please provide me any suggestion to do this in c language only.
The given question is different from my question because in that question they checking the behaviour of the string literals bu for my case I am looking to assigns concatenate value to variable str. And its solution changing pointer to an array but I cannot change because its value is using many functions for my work.
Your function combine() calls free() on its first argument. In your fun() call, which is passed from fun() which points to a string literal in your code.
You cannot call free() on a string literal, that's undefined behaviour. I suggest you to restructure your code so that combine() no longer calls free() on its first argument. Freeing memory should be the callers responsibility.
I would suggest pairs of allocation/deallocation functions:
char * combine_allocate(const char *a, const char *b) {
char* result = malloc(...)
combine ...
return result;
}
void combine_deallocate(char* p) { free(p); }
Having that:
char* a = initial_allocate();
char* b = initial_allocate();
char* c = combine_allocate(a, b);
initial_deallocate(a);
initial_deallocate(b);
// ... use c
combine_deallocate(c)
You may omit (and should) initial_allocate/initial_deallocate for string literals.
It might be a bit too verbose, but object oriented C does nothing else (with nicer function names).
I want to write a program in C that displays each word of a whole sentence (taken as input) at a seperate line. This is what I have done so far:
void manipulate(char *buffer);
int get_words(char *buffer);
int main(){
char buff[100];
printf("sizeof %d\nstrlen %d\n", sizeof(buff), strlen(buff)); // Debugging reasons
bzero(buff, sizeof(buff));
printf("Give me the text:\n");
fgets(buff, sizeof(buff), stdin);
manipulate(buff);
return 0;
}
int get_words(char *buffer){ // Function that gets the word count, by counting the spaces.
int count;
int wordcount = 0;
char ch;
for (count = 0; count < strlen(buffer); count ++){
ch = buffer[count];
if((isblank(ch)) || (buffer[count] == '\0')){ // if the character is blank, or null byte add 1 to the wordcounter
wordcount += 1;
}
}
printf("%d\n\n", wordcount);
return wordcount;
}
void manipulate(char *buffer){
int words = get_words(buffer);
char *newbuff[words];
char *ptr;
int count = 0;
int count2 = 0;
char ch = '\n';
ptr = buffer;
bzero(newbuff, sizeof(newbuff));
for (count = 0; count < 100; count ++){
ch = buffer[count];
if (isblank(ch) || buffer[count] == '\0'){
buffer[count] = '\0';
if((newbuff[count2] = (char *)malloc(strlen(buffer))) == NULL) {
printf("MALLOC ERROR!\n");
exit(-1);
}
strcpy(newbuff[count2], ptr);
printf("\n%s\n",newbuff[count2]);
ptr = &buffer[count + 1];
count2 ++;
}
}
}
Although the output is what I want, I have really many black spaces after the final word displayed, and the malloc() returns NULL so the MALLOC ERROR! is displayed in the end.
I can understand that there is a mistake at my malloc() implementation, but I do not know what it is.
Is there another more elegant or generally better way to do it?
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
Take a look at this, and use whitespace characters as the delimiter. If you need more hints let me know.
From the website:
char * strtok ( char * str, const char * delimiters );
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.
Parameters
str
C string to truncate.
Notice that this string is modified by being broken into smaller strings (tokens).
Alternativelly [sic], a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
delimiters
C string containing the delimiter characters.
These may vary from one call to another.
Return Value
A pointer to the last token found in string.
A null pointer is returned if there are no tokens left to retrieve.
Example
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
For the fun of it here's an implementation based on the callback approach:
const char* find(const char* s,
const char* e,
int (*pred)(char))
{
while( s != e && !pred(*s) ) ++s;
return s;
}
void split_on_ws(const char* s,
const char* e,
void (*callback)(const char*, const char*))
{
const char* p = s;
while( s != e ) {
s = find(s, e, isspace);
callback(p, s);
p = s = find(s, e, isnotspace);
}
}
void handle_word(const char* s, const char* e)
{
// handle the word that starts at s and ends at e
}
int main()
{
split_on_ws(some_str, some_str + strlen(some_str), handle_word);
}
malloc(0) may (optionally) return NULL, depending on the implementation. Do you realize why you may be calling malloc(0)? Or more precisely, do you see where you are reading and writing beyond the size of your arrays?
Consider using strtok_r, as others have suggested, or something like:
void printWords(const char *string) {
// Make a local copy of the string that we can manipulate.
char * const copy = strdup(string);
char *space = copy;
// Find the next space in the string, and replace it with a newline.
while (space = strchr(space,' ')) *space = '\n';
// There are no more spaces in the string; print out our modified copy.
printf("%s\n", copy);
// Free our local copy
free(copy);
}
Something going wrong is get_words() always returning one less than the actual word count, so eventually you attempt to:
char *newbuff[words]; /* Words is one less than the actual number,
so this is declared to be too small. */
newbuff[count2] = (char *)malloc(strlen(buffer))
count2, eventually, is always one more than the number of elements you've declared for newbuff[]. Why malloc() isn't returning a valid ptr, though, I don't know.
You should be malloc'ing strlen(ptr), not strlen(buf). Also, your count2 should be limited to the number of words. When you get to the end of your string, you continue going over the zeros in your buffer and adding zero size strings to your array.
Just as an idea of a different style of string manipulation in C, here's an example which does not modify the source string, and does not use malloc. To find spaces I use the libc function strpbrk.
int print_words(const char *string, FILE *f)
{
static const char space_characters[] = " \t";
const char *next_space;
// Find the next space in the string
//
while ((next_space = strpbrk(string, space_characters)))
{
const char *p;
// If there are non-space characters between what we found
// and what we started from, print them.
//
if (next_space != string)
{
for (p=string; p<next_space; p++)
{
if(fputc(*p, f) == EOF)
{
return -1;
}
}
// Print a newline
//
if (fputc('\n', f) == EOF)
{
return -1;
}
}
// Advance next_space until we hit a non-space character
//
while (*next_space && strchr(space_characters, *next_space))
{
next_space++;
}
// Advance the string
//
string = next_space;
}
// Handle the case where there are no spaces left in the string
//
if (*string)
{
if (fprintf(f, "%s\n", string) < 0)
{
return -1;
}
}
return 0;
}
you can scan the char array looking for the token if you found it just print new line else print the char.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
int len = strlen(s);
char delim =' ';
for(int i = 0; i < len; i++) {
if(s[i] == delim) {
printf("\n");
}
else {
printf("%c", s[i]);
}
}
free(s);
return 0;
}
char arr[50];
gets(arr);
int c=0,i,l;
l=strlen(arr);
for(i=0;i<l;i++){
if(arr[i]==32){
printf("\n");
}
else
printf("%c",arr[i]);
}