I'm writing a program in which a function that reverses each word in a string. When I call the function, it will pass the pointer to source string and then return the pointer to modified string.
input: Why always me?
output: yhW syawla ?em
But for some reason, it is not working. No errors. And logic seemed fine to me (i'm not that good with c, btw)
Here's my code:
char *reverse_words(char *source_string)
{
char *startW, *endW;
startW = source_string;
while(*startW != '\0')
{
while(*startW == ' ')
startW++; //Skip multiple spaces in the beginning
endW = startW;
while(*endW != ' ' || *endW != '\0')
endW++;
char *_start = startW;
char *_end = endW - 1;
char temp;
while(_end > _start)
{
temp = *_start;
*_start++ = *_end;
*_end++ = temp;
}
startW = endW;
}
return source_string;
}
void main() {
char *s;
s = malloc(256);
gets(s);
printf("%s\n", s);
char *r = reverse_words(s);
printf("\nReversed String : %s",r);
free(s);
free(r);
}
Also, i'm using codeblocks IDE. After I input my string, it prints it back (scanf and printf in main) and after that, the program stops working.
Any help would be appreciated.
First,
while(*endW != ' ' || *endW != '\0')
is an infinite loop, try this instead:
while(*endW != ' ' && *endW != '\0')
Second,
*_end++ = temp;
should be this:
*_end-- = temp;
In the innermost while(_end > _start) loop you increment both _start and _end. So the condition will never become false. (Well, not until _end overflows.)
I'd recommend figuring out how to do step-by-step debugging in your IDE. Then you can easily understand what exactly goes wrong in a case like this, without simulating the execution in your head.
#include <stdio.h>
#include <stdlib.h>
char *reverse_words(const char *source_string){
const char *startW, *endW;
char *p, *rev = malloc(256);
startW = source_string;
p = rev;
while(*startW != '\0'){
while(*startW == ' ')
*p++ = *startW++;
if(!*startW)
break;
endW = startW;
while(*endW != ' ' && *endW != '\0')
endW++;
const char *endW2 = endW;
do{
*p++ = *--endW;
}while(startW!=endW);
startW = endW2;
}
*p = '\0';
return rev;
}
int main() {
char s[256];
scanf("%255[^\n]", s);
printf("%s,\n", s);
char *r = reverse_words(s);
printf("\nReversed String : %s.", r);
free(r);
return 0;
}
Related
I tried to write a function that gets a string and creates a new string but without multiple spaces (leaving only 1 space between words).
So far I wrote this, but for some reason it crashs and the debugger shows nothing.
I also don't know where do I need to put the free function...
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* upgradestring(char* oldtext);
int main()
{
char str1[] = "Chocolate Can Boost Your Workout" ;
printf("%s\n", str1);
printf("\n%s\n", upgradestring(str1));
return 0;
}
char* upgradestring(char* oldtext)
{
int i,j, count = 1;
char *newstr;
for (i = 0; oldtext[i] != '\0'; i++)
{
if (oldtext[i] != ' ')
count++;
else if (oldtext[i - 1] != ' ')
count++;
}
newstr = (char*)malloc(count * sizeof(char));
if (newstr == NULL)
exit(1);
for (i = 0, j = 0; (oldtext[i] != '\0')|| j<(count+1); i++)
{
if (oldtext[i] != ' ')
{
newstr[j] = oldtext[i];
j++;
}
else if (oldtext[i - 1] != ' ')
{
newstr[j] = oldtext[i];
j++;
}
}
return newstr;
}
You're addressing [i-1] and it's not within the range of the original array if i==0.
Here's how you could do it:
Simply copy one by one and if the char is ' ', keep skipping while it is ' ', otherwise advance by one.
static size_t newlen(char const *o)
{
size_t r=0;
while(*o){
r++;
if(*o==' ')
while(*o==' ')
o++;
else
o++;
}
return r;
}
char *upgradestring(char const *o)
{
char *r, *p;
size_t len = newlen(o);
if( 0==(r = malloc(len+1)))
return 0;
r[len]=0;
for(p=r;*o;){
*p++=*o;
if(*o==' ')
while(*o==' ')
o++;
else
o++;
}
return r;
}
int main()
{
char str1[] = "Chocolate Can Boost Your Workout" ;
char *new;
printf("%s\n", str1);
if(0 == (new = upgradestring(str1)))
return 1;
printf("%s\n", new);
free(new);
}
Failures to allocate are best signalled by return codes (you wouldn't want a library function to abort your program if it fails).
In order to be able to free the returned string, you first must capture it in a variable.
Good attempt, but let's focus on when you need to free your memory. You allocate dynamically the memory inside the function, then call the function inside a printf, which will allow the string to print, but how will you deallocate it? Use a pointer to assign the return value of your function, print it, and then free it!
Moreover, you need to allocate space for as many characters the new string has, plus one for the null terminator, since C strings require that to work smoothly with functions coming from headers, such as printf().
Furthermore, we do not cast what malloc() returns in C, read more here.
Also this:
else if (oldtext[i - 1] != ' ')
should be written as:
else if (i != 0 && oldtext[i - 1] != ' ')
to avoid accessing oldtext[-1] which is out of bounds, when i is 0.
Lastly, the condition you used when populating the new string, would be better with a logical AND, instead of an OR, since we have to stop as soon as either condition is false (we do not want to read past the null terminator of the original string, or past the size of the new string).
Putting everything together, we:
#include <stdio.h>
#include <stdlib.h>
char* upgradestring(char* oldtext)
{
int i, j, count = 0;
// compute 'count'
for(i = 0; oldtext[i]; i++)
{
if (oldtext[i] != ' ')
count++;
else if (i != 0 && oldtext[i - 1] != ' ')
count++;
}
char* newstr = malloc(count + 1); // PLUS ONE for the null terminator
if(!newstr) // check if malloc failed
{
printf("Malloc failed\n");
return 0;
}
// populate 'newstr'. We need to stop when either condition is false
for (i = 0, j = 0; (oldtext[i]) && j<(count+1); i++)
{
// Same as your code
}
// Assign the null terminator!
newstr[j] = '\0';
return newstr;
}
int main(void) {
char str1[] = "Chocolate Can Boost Your Workout" ;
// store the result of your function into 'newstr'
char* newstr = upgradestring(str1);
// print it
printf("%s\n", newstr);
// free it, since you no longer need it!
free(newstr);
return 0;
}
Output:
Chocolate Can Boost Your Workout
#include <stdio.h>
#include <stdlib.h>
char *upgradestring(char *oldtext)
{
size_t len,src,dst,spc;
char *result;
// First pass: count needed size
for (len=src=spc=0;oldtext[src]; src++){
if (oldtext[src] != ' ') spc=0; // non-space needs space
else if(spc++) continue; // skip non first space
len++;
}
result= malloc (1+len);
// Second pass: copy(K&R style)
for (dst=src=spc=0; (result[dst] = oldtext[src]) ; src++){
if (oldtext[src] != ' ') spc=0; // non-space: rest counter
else if(spc++) continue; // skip non-first space
dst++;
}
return result;
}
Simplified version: dont calculate the size in a first pass, but start with the same size as the original, and resize after the second pass. (strdup() can be replaced by strlen+malloc+memcpy)
char * strdup(char *);
char *upgradestring2(char *oldtext)
{
size_t src,dst,spc;
char *result;
result= strdup (oldtext);
// edit the copy, skipping all spaces except the first
for (dst=src=spc=0; result[src] ; src++){
if (result[src] != ' ') spc=0; // non-space:reset counter
else if(spc++) continue; // skip space,except the first
result[dst++] = result[src]; // Copy
}
result[dst] = 0;// terminate string;
// result=realloc(result, dst+1);
return result;
}
For starters neither declaration from the header <string.h> is used in your program. Thus this directive
#include <string.h>
may be removed from the program.
According to the C Standard the function main without parameters shall be declared like
int main( void )
The function with the strange name upgradestring:) does not change the argument. Hence it should be declared like
char* upgradestring( const char* oldtext);
^^^^^
Take into account that the source string can start with blanks. In this case statements like this
else if (oldtext[i - 1] != ' ')
count++;
result in undefined behavior because there is an attempt to access memory beyond the string when i is equal to 0.
The condition
(oldtext[i] != '\0')|| j<(count+1);
should be written at least like
(oldtext[i] != '\0') && j<(count+1);
^^^
though it is enough to check the index j because it can not be greater than the length of the source string.
You forgot to append the result string with the terminating zero '\0'.
Also it is not a good idea to exit the function with this statement
exit(1);
In this case you could just return a null pointer.
And the allocated memory should be freed before exiting the program.
As it has been mentioned before a source string can start with spaces and also have a redundant trailing space. I think it will be logically consistent to exclude them from the result string.
Usually the space character is considered in pair with the tab character. Moreover C has a special function isblank declared in the header <ctype.h> that checks whether a character is a space or a blank. (As far as I know the MS VS does not support this function)
Taking all this into account the function can be defined the following way as it is shown in the demonstrative program.
#include <stdio.h>
#include <stdlib.h>
char * trim_blanks( const char *s )
{
size_t n = 0;
const char *p = s;
// skip leading blanks
while ( *p == ' ' || *p == '\t' ) ++p;
_Bool last_blank = 0;
for ( ; *p; ++p )
{
++n;
if ( ( last_blank = ( *p == ' ' || *p == '\t' ) ) )
{
while ( p[1] == ' ' || p[1] == '\t' ) ++p;
}
}
if ( last_blank ) --n;
char *q = malloc( n + 1 );
if ( q )
{
p = s;
// skip leading blanks
while ( *p == ' ' || *p == '\t' ) ++p;
size_t i = 0;
for ( ; i < n; i++, ++p )
{
q[i] = *p == '\t' ? ' ' : *p;
if ( q[i] == ' ' )
{
while ( p[1] == ' ' || p[1] == '\t' ) ++p;
}
}
q[i] = '\0';
}
return q;
}
int main(void)
{
char s[] = "\t\tChocolate \t Can \t Boost Your Workout ";
printf( "\"%s\"\n", s );
char *t = trim_blanks( s );
printf( "\"%s\"\n", t );
free( t );
return 0;
}
The program output is
" Chocolate Can Boost Your Workout "
"Chocolate Can Boost Your Workout"
I'm trying to make a method called "censor" that finds the 4 letter words in a string using 2 methods ive already made, the new method has to void censor(*start), an explanation as to what I'm doing wrong would be great, thanks!
void four_stars(char *start){
int count = 0;
int c = 42;
printf("entered\n");
while(count < 4){
*start = c;
start++;
count++;
}
}
and
char* find_blank(char *start){
char c;
int space = 127;
int null = 0;
while(*start){
c = *start;
int asciiVal = c;
if(asciiVal == 32 || asciiVal == 3){
return start;
}
start++;
}
}
the main method that im using to test it is:
int main(){
char myString3[25] = "Test a duck";
printf("The string before: %s\n", myString3);
censor(myString3);
printf("The new string: %s", myString3);
return 0;
}
And what I have is
void censor(char *start){
char* c = start;
while(*start){
int i = (int)find_blank(start) - (int)start;
start = start + i + 1;
c = start;
if((int)find_blank(start) - (int)c == 4){
four_stars(start);
}
start++;
}
}
#include <stdio.h>
void four_stars(char *start){
int count = 0;
int c = '*';
//printf("entered\n");
while(count < 4){
*start = c;
start++;
count++;
}
}
char* find_blank(char *start){
char c;
while(*start){
c = *start;
if(c == ' ' || c == '\t' || c == '\n'){
return start;
}
start++;
}
return start;
}
char* find_not_blank(char *start){
char c;
while(*start){
c = *start;
if(c != ' ' && c != '\t' && c != '\n'){
return start;
}
start++;
}
return NULL;
}
void censor(char *start){
while(start = find_not_blank(start)){
int len = find_blank(start) - start;
if(len == 4){
four_stars(start);
}
start += len;
}
}
int main(){
char myString3[25] = "Test a duck";
printf("The string before: %s\n", myString3);
censor(myString3);
printf("The new string: %s", myString3);
return 0;
}
There are a number of ways to do this. When learning C, one of the challenges is getting comfortable with the use of pointers for scanning strings. Along with that comes learning what C library functions are available to help with the scanning when needed. (you can always do it with pointers alone, but there are useful functions that can save you a lot of comparison work)
There are a couple of complicating factors to consider in scanning for 4-letter words. Most notable punctuation as word ends. One shortcut for handling multiple possible word ends is simply to create a string holding a collection of characters that can be at the end of a word instead of simple a space. Then the C library function strchr can be used to check if your ending character is in that collection.
Utilizing that, here is a short example of one approach to scanning a string for 4-letter words that may help you along:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void censor (char *s)
{
if (!s) return; /* validate s */
char *sp = s; /* start pointer */
char *ep = s; /* end pointer */
char *termchr = " ,.\n\t\0"; /* str of word ends */
while (*ep) /* for each char in string */
{
if (strchr (termchr, *ep)) /* if char in termchr */
{ /* and num chars == 4 */
if (ep - ((sp > s) ? ++sp : sp) == 4)
{
while (sp < ep) /* replace with '*' */
*sp++ = '*';
}
else
sp = ep; /* if not, just advance sp */
}
ep++;
}
}
int main (int argc, char **argv) {
if (argc < 2) {
fprintf (stderr, "\n error: insufficient input. Usage: %s <string>\n\n", argv[0]);
return 1;
}
char *str = strdup (argv[1]); /* make a copy to prevent clobbering argv[1] */
printf (" original string: %s\n", str);
censor (str);
printf (" censored string: %s\n", str);
return 0;
}
output:
$ ./bin/censor "A sting that has duck you dude."
original string: A sting that has duck you dude.
censored string: A sting **** has **** you ****.
Note: ((sp > s) ? ++sp : sp) is a simple test that says if I'm at the beginning, don't advance sp before comparing needed because your are at the beginning of a word already (the first word), not on the last termchr you found. You will probably want to come up with a scheme to exclude common words from replacement so you are not censoring words like this, that, with, most, good, word(s). That's left to you.
Just a quick one: in C I have a buffer full of data like below:
char buffer[255]="CODE=12345-MODE-12453-CODE1-12355"
My question is how to search through this. For example for the CODE=12345, section bear in mind that the numbers change, so I would like to search like this CODE=***** using wildcard or preset amount of spaces after the CODE= part.
This method wont compile last one left to try
#include <stdio.h>
#include <string.h>
#include <windows.h>
int main ()
{
char buf[255]="CODE=12345-MODE-12453-CODE1-12355";
#define TRIMSPACES(p) while(*p != '\0' && isspace((unsigned char)*p) != 0) ++p
#define NSTRIP(p, n) p += n
#define STRIP(p) ++p
char* getcode(const char *input)
{
char *p = (char*) input, *buf, *pbuf;
if((buf = malloc(256)) == NULL)
return NULL;
pbuf = buf;
while(*p != '\0') {
if(strncmp(p, "CODE", 3) == 0) {
NSTRIP(p, 4); //remove 'code'
TRIMSPACES(p);//trim white-space after 'code'
if(*p != '=')
return NULL;
STRIP(p); // remove '='
TRIMSPACES(p); //trim white-spaces after '='
/* copy the value until found a '-'
note: you must be control the size of it,
for avoid overflow. we allocated size, that's 256
or do subsequent calls to realloc()
*/
while(*p != '\0' && *p != '-')
*pbuf ++ = *p++;
// break;
}
p ++;
}
//put 0-terminator.
*pbuf ++ = '\0';
return buf;
}
//
}
You could use the sscanf() function:
int number;
sscanf(buffer, "CODE = %i", &number);
for that to work well your buffer has to be null terminated.
Another way to do it instead of sscanf():
char *input, *code;
input = strstr(buf, "CODE");
if(input == NULL) {
printf("Not found CODE=\n");
return -1;
}
code = strtok(strdup(input), "=");
if(code != NULL) {
code = strtok(NULL, "-");
printf("%s\n", code); // code = atoi(code);
} else {
//not found '='
}
Or more robust way.. a bit more complex:
#define TRIMSPACES(p) while(*p != '\0' && isspace((unsigned char)*p) != 0) ++p
#define NSTRIP(p, n) p += n
#define STRIP(p) ++p
char* getcode(const char *input, size_t limit)
{
char *p = (char*) input, *buf, *pbuf;
size_t i = 0;
while(*p != '\0') {
if(strncmp(p, "CODE", 3) == 0) {
NSTRIP(p, 4); //remove 'code'
TRIMSPACES(p);//trim all white-spaces after 'code'
/* check we have a '=' after CODE (without spaces).
if there is not, returns NULL
*/
if(*p != '=')
return NULL;
/* ok. We have.. now we don't need of it
just remove it from we output string.
*/
STRIP(p);
/* remove again all white-spaces after '=' */
TRIMSPACES(p);
/* the rest of string is not valid,
because are white-spaces values.
*/
if(*p == '\0')
return NULL;
/* allocate space for store the value
between code= and -.
this limit is set into second parameter.
*/
if((buf = malloc(limit)) == NULL)
return NULL;
/* copy the value until found a '-'
note: you must be control the size of it,
for don't overflow. we allocated 256 bytes.
if the string is greater it, do implementation with
subjecents call to realloc()
*/
pbuf = buf;
while(*p != '\0' && *p != '-' && i < limit) {
*pbuf ++ = *p++;
i ++;
}
*pbuf ++ = '\0';
return buf;
}
p ++;
}
return NULL;
}
And then:
char buf[255] = "foo baa CODE = 12345-MODE-12453-CODE-12355";
char *code = getcode(buf,256);
if(code != NULL) {
printf("code = %s\n", code);
free(code);
} else {
printf("Not found code.\n");
}
output:
code = 12345
Check out this online.
if you want to don't differentiate case, you can use the strncasecmp() that's POSIX function.
Assuming the CODE= part always comes at the beginning of the string, it's pretty easy:
sscanf(buffer, "CODE = %d", &number);
...but you want buffer to be char[255], not unsigned long.
Edit: If the CODE= part isn't necessarily at the beginning of the string, you can use strstr to find CODE in the buffer, do your sscanf starting from that point, then look immediately following that:
int codes[256];
char *pos = buffer;
size_t current = 0;
while ((pos=strstr(pos, "CODE")) != NULL) {
if (sscanf(pos, "CODE = %d", codes+current))
++current;
pos += 4;
}
Edit2:
For example, you'd use this something like this:
#include <stdio.h>
#include <string.h>
#include <windows.h>
int main ()
{
// This is full of other junk as well
char buffer[255]="CODE=12345 MODE-12453 CODE=12355" ;
int i;
int codes[256];
char *pos = buffer;
size_t current = 0;
while ((pos=strstr(pos, "CODE")) != NULL) {
if (sscanf(pos, "CODE = %d", codes+current))
++current;
pos += 4;
}
for (i=0; i<current; i++)
printf("%d\n", codes[i]);
return 0;
}
For me, this produces the following output:
12345
12355
...correctly reading the two "CODE=xxx" sections, but skipings over the "MODE=yyy" section.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *getcode(const char *str, const char *pattern){
//pattern: char is match, space is skip, * is collect
static const char *p=NULL;
char *retbuf, *pat;
int i, match, skip, patlen;
if(str != NULL) p=str;
if(p==NULL || *p=='\0') return NULL;
if(NULL==(retbuf=(char*)malloc((strlen(p)+1)*sizeof(char))))
return NULL;
pat = (char*)pattern;
patlen = strlen(pat);
i = match = skip = 0;
while(*p){
if(isspace(*p)){
++p;
++skip;
continue;
}
if(*pat){
if(*p == *pat){
++match;
++p;
++pat;
} else if(*pat == '*'){
++match;
retbuf[i++]=*p++;
++pat;
} else {
if(match){//reset
pat=(char*)pattern;
p -= match + skip -1;
i = match = skip = 0;
} else //next
++p;
}
} else {
break;
}
}
if(i){//has match
retbuf[i++]='\0';
retbuf=realloc(retbuf, i);
return retbuf;
} else {
free(retbuf);
return NULL;
}
}
int main (){
char *code;
code=getcode("CODE=12345-MODE-12453-CODE1-12355", "CODE=*****");
printf("\"%s\"\n",code);//"12345"
free(code);
code=getcode(" CODE = 12345-MODE-12453-CODE1-12355", "CODE=*****");
printf("\"%s\"\n",code);//"12345"
free(code);
code=getcode("CODE-12345-MODE-12453-CODE1-12355", "CODE=*****");
if(code==NULL)printf("not match\n");//not match
code=getcode("CODE=12345-MODE-12453-CODE=12355", "CODE=*****");
printf("\"%s\"\n",code);//"12345"
free(code);
code=getcode(NULL, "CODE=*****");
printf("\"%s\"\n",code);//"12355"
free(code);
code=getcode("CODE=12345-MODE-12453-CODE1-12355", "CODE=*****");
printf("\"%s\"\n",code);//"12345"
free(code);
code=getcode(NULL, "CODE1-*****");
printf("\"%s\"\n",code);//"12355"
free(code);
return 0;
}
I have a string as const char *str = "Hello, this is an example of my string";
How could I get everything after the first comma. So for this instance: this is an example of my string
Thanks
You can do something similar to what you've posted:
char *a, *b;
int i = 0;
while (a[i] && a[i] != ',')
i++;
if (a[i] == ',') {
printf("%s", a + i + 1);
} else {
printf("Comma separator not found");
}
Alternatively, you can take a look at strtok and strstr.
With strstr you can do:
char *a = "hello, this is an example of my string";
char *b = ",";
char *c;
c = strstr(a, b);
if (c != NULL)
printf("%s", c + 1);
else
printf("Comma separator not found");
Since you want a tail of the original string, there's no need to copy or modify anything, so:
#include <string.h>
...
const char *result = strchr(str, ',');
if (result) {
printf("Found: %s\n", result+1);
} else {
printf("Not found\n");
}
If you want ideas how to do it yourself (useful if you later want to do something similar but not identical), take a look at an implementation of strchr.
const char *result;
for(result = str; *result; result++)
if(*result == ',')
{
result++;
break;
}
//result points to the first character after the comma
After this code, result points to the string starting right after the comma. Or to the final '\0' (empty string), if there is no comma in the string.
You have the right idea, the following programs is one way to do it:
#include <stdio.h>
#include <string.h>
static char *comma (char *s) {
char *cpos = strchr (s, ',');
if (cpos == NULL)
return s;
return cpos + 1;
}
int main (int c, char *v[]) {
int i;
if (c >1 )
for (i = 1; i < c; i++)
printf ("[%s] -> [%s]\n", v[i], comma (v[i]));
return 0;
}
It produced the following output:
$ commas hello,there goodbye two,commas,here
[hello,there] -> [there]
[goodbye] -> [goodbye]
[two,commas,here] -> [commas,here]
Well I'm looking for a function that reduce multiple space characters ' ' in a string.
For example for string s given :
s="hello__________world____!"
The function must return "hello_world_!"
In python we can do it via regexp simply as:
re.sub("\s+", " ", s);
A version that modifies the string in place, run it on a copy if the original must be preserved:
void compress_spaces(char *str)
{
char *dst = str;
for (; *str; ++str) {
*dst++ = *str;
if (isspace(*str)) {
do ++str;
while (isspace(*str));
--str;
}
}
*dst = 0;
}
There is no such function in the C standard library. One must write a function to do so or use a third-party library.
The following function should do the trick. Use the source string as the destination pointer to perform the operation in place. Otherwise, ensure that the destination buffer is sufficiently sized.
void
simplifyWhitespace(char * dst, const char * src)
{
for (; *src; ++dst, ++src) {
*dst = *src;
if (isspace(*src))
while (isspace(*(src + 1)))
++src;
}
*dst = '\0';
}
void remove_more_than_one_space(char *dest, char *src)
{
int i, y;
assert(dest && src);
for(i=0, y=0; src[i] != '\0'; i++, y++) {
if(src[i] == ' ' && src[i+1] == ' ') {
/* let's skip this copy and reduce the y index*/
y--;
continue;
}
/* copy normally */
dest[y] = src[i];
}
dest[y] = '\0';
}
int main()
{
char src[] = "Hello World ! !! !";
char dest[strlen(src) + 1];
remove_more_than_one_space(dest, src);
printf("%s\n", dest);
}
I just made this, hope it helps.
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
char word[100];
gets(word);
//the word has more than a single space in between the words
int i=0,l,j;
l=strlen(word);
for (i=0;i<l;i++)
{
if(word[i]==' '&&word[i+1]==' ')
{
for(j=i+1;j<l;j++)
word[j]=word[j+1];
}
}
puts(word);
return 0;
}
This code is very simple and it worked like a charm for me. I don't know if this code will have some other problems I haven't come across, but for now this works.
I'm just learning C, so I'm using much more basic code. I'm reading the first chapter of "The C programming language", and I was trying to find the answer to a task set in there.
This is what I came up with:
#include <stdio.h>
int main()
{
/* Set two integers:
c is the character being assessed,
lastspace is 1 if the lastcharacter was a space*/
int c, lastspace;
lastspace = 0;
/* This while loop will exit if the character is EOF
The first "If block" is true if the character is not a space,
and just prints the character
It also tells us that the lastcharacter was not a space
The else block will run if the character is a space
Then the second IF block will run if the last character
was not also a space (and will print just one space) */
while((c = getchar()) != EOF){
if (c != ' '){
putchar(c);
lastspace = 0;
}
else {
if (lastspace != 1)
putchar(c);
lastspace = 1;
}
}
return 0;
}
Hope that helps!
Also, I am well aware that this code is perhaps not optimised, but it should be simple for a beginner like me to understand!
Thanks, Phil
another way of doing this to print only the first occurrence of space until next character comes, here is my brute force solution.
#include<stdio.h>
typedef int bool;
#define True 1
#define False 0
int main()
{
int t;
bool flag = False;
while ((t = getchar()) != EOF)
if (t == ' ' && !flag)
{
putchar(' ');
flag = True; // flag is true for the first occurence of space
}
else if(t == ' '&& flag)
continue;
else
{
putchar(t);
flag = False;
}
return 0;
}
hope it helps.