Home > other >  Reverse the words in a sentence using two while loops
Reverse the words in a sentence using two while loops

Time:03-13

I cant get the right output and I wonder where my mistake is. Probably there are mistakes in loops in the counting reverse. The main problem in my whole code is that it only outputs marks but not words. Also the program must end automatically when putting these three punctuation and shows the output.

This is the expected behavior:

Input: my name is jake.//terminates when putting . and automatically shows the output

Output: jake is name my.

Here is the program fragment of my first loop:

#include <stdio.h>

#define N 70

int main(void) {

    char array[N] = { 0 };

    char *p;
    char mark = 0;
    int c;
    p = array;

    scanf("%d", &c);

    while ((c = getchar()) != '\n') {
        if (p < array   N) {
            if (c == '.' || c == '!' || c == '?')
                mark = c;
            if (c == ' ') {
                *p = '\0';
                *p  ;
            } else
                *p = c;
        }
    }
    *p = '\0';
    while (--p > array) {
        if (p[1])
            printf("%s", p   1);
    }
    printf("%s", array);
    if (mark)
        printf("%c", mark);
}

CodePudding user response:

Your code with little modifications:

#include <stdio.h>

#define N 70

int main (void) {

    char array[N 1] = { 0 };

    char* p;
    char mark = 0;
    int c;
    p = array;

    //scanf ("%d", &c); //serves no purpose : are you reading sentence length here?

    while ( (c = getchar()) != '\n') {
        if (p < array   N) {
            if (c == '.' || c == '!' || c == '?') {
                mark = c;
                *p   = '\0';
                break;          // stop reading input
            } else if (c == ' ') {
                *p   = '\0';
            } else
                *p   = c;
        }
    }
    *p = '\0';
    while (--p > array) {
        if ('\0' == *p && '\0' != *(p   1))
            printf ("%s ", p   1);
    }
    printf ("%s", array);
    if (mark)
        printf ("%c", mark);

    return 0;
}

There is a better way, but that will make use of string library functions.

CodePudding user response:

Here is an alternative where the original string is not modified:

#include <stdio.h>
#include <string.h>

void print_swap(const char *s) {
    int p1, p2, tail = strcspn(s, ".!?\n");
    for (p1 = p2 = tail; p1 > 0; p1--) {
        if (s[p1 - 1] == ' ') {
            printf("%.*s ", p2 - p1, s   p1);
            p2 = p1 - 1;
        }
    }
    printf("%.*s%s", p2, s, s   tail);
}

int main() {
    char array[80];
    if (fgets(array, sizeof array, stdin))
        print_swap(array);
    return 0;
}
  •  Tags:  
  • c
  • Related