C language. work with text


Joined
Dec 10, 2021
Messages
4
Reaction score
0
hello, I just recently started learning C language. Please do not swear at me))

i want to make a program
I enter text from the keyboard into the console and I want the program to swap the first and last letter of each word and count how many words are in the sentence.

I found a program on the Internet that swaps letters and altered it a little

how can i fix it?

I did it but he only counts the words

C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


char * swap(const char * str);
 
int main(void)
{
    char s[200];
    int count = 0, i;
    printf("Enter the string:\n");
    scanf("%[^\n]s", s);
    for (i = 0;s[i] != '\0';i++)

    {
        if (s[i] == ' ' && s[i+1] != ' ')
            count++;   
    }
    printf("words: %d\n", count + 1);
}
 
char * swap(char * s)
{
    const size_t length = strlen(s);
    char * ch = malloc(length + 1);
 
    strncat(ch, s, length);
    ch[length] = '\0';
 
    char * k = ch;
 
    while (k != NULL)
    {
        char * last = strchr(k, ' ');
 
        if (last != NULL)
        {
            char t = *k;
            *k = *(last - 1);
            *(last - 1) = t;
            k = last + 1;
        }
        else
        {
            char t = *(k);
            *k = *(ch + length - 1);
            *(ch + length - 1) = t;
            k = NULL;
        }
    }
 
    return ch;
}
 
Ad

Advertisements

Joined
Mar 3, 2021
Messages
243
Reaction score
29
We've got two problems here. First, the declaration of swap doesn't match the definition (check the arguments, const char* vs char*). Second, you're not actually calling swap. Throw the following in after you print the word count.

C:
printf("%s\n", swap(s));
 
Joined
Dec 10, 2021
Messages
4
Reaction score
0
Nothing changed. maybe I put it in the wrong place?
char * swap(const char* vs char*);

int main(void)
{
char s[200];
int count = 0, i;
printf("Enter the string:\n");
scanf("%[^\n]s", s);
for (i = 0;s != '\0';i++)

{
if (s == ' ' && s[i+1] != ' ')
count++;
}
printf("words: %d\n", count + 1);


printf("%s\n", swap(s));


}
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top