I am trying to make a program that would take a sentence from the user and reverse the order of the words while keeping the special characters ['.','?','!'] at the end.
the problem I'm getting is that I get weird symbols after the last word and the special character.
I am programming using C.
I think it's because the last element printed is not a '\0'.
but I don't know how to fix that.
My code:
#include <ctype.h>
#define N 200
int main()
{
char arr[N] = { 0 };
char* p, * q, mark = 0;
int c;
p = arr;
printf("Enter a sentence: ");
while ((c = getchar()) != '\n' && p < arr + N)
{
if (c == '?' || c == '.' || c == '!')
{
mark = c;
break;
}
else
*p++ = c;
}
*p = '\0';
printf("Reversal of sentence: ");
while (p >= arr)
{
while (*--p != ' ' && p != arr);
if (p == arr) {q = arr;}
else {q = p + 1;}
while (*q != '\0' && *q != ' ')
{
printf("%c", *q++);
}
if (p >= arr)
{
printf(" ");
}
}
printf("%c", mark);
printf("\n");
return 0;
}
I've fixed the overflow error when reading the sentence by removing the \0 termination. The input string is never used by anything that cares. I've also added a check for End-Of-File.
Next I changed the reversal loop to not underflow and fixed outputing an extra ' ' before the mark.
Last the printf calls can use putchar instead.
#include <ctype.h>
#include <stdio.h>
#define N 200
int main()
{
char arr[N] = { 0 }; // initialization optional, nothing cares
char* p, * q, mark = 0;
int c;
p = arr;
printf("Enter a sentence: ");
while ((c = getchar()) != '\n' && c != EOF && p < arr + N)
{
if (c == '?' || c == '.' || c == '!')
{
mark = c;
break;
}
else
*p++ = c;
}
printf("Reversal of sentence: ");
while (p > arr)
{
while (*--p != ' ' && p != arr);
if (p == arr) {q = arr;}
else {q = p + 1;}
while (*q != '\0' && *q != ' ')
{
putchar(*q++);
}
if (p > arr)
{
putchar(' ');
}
}
putchar(mark);
putchar('\n');
return 0;
}
Related
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);
}
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.
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;
}
Question: Define an int function that removes all consecutive vowel repetitions from a string. The function should return the number of vowels removed and present the string without duplicates.
I am PT so Vogais is Vowels; Digite uma String is Write one String. A String sem duplicados fica assim ' %s ' e foram retiradas %d vogais is The string without duplicates is ' %s ' and where removed %d vowels.
Explanation: In portuguese we have some words with two consecutive vowels like: coordenador, coordenação (chqrlie example). But in thouse cases should be ignored in the context of this problem.
Problem: When I test a string like 'ooooo' it says the string without duplicate vogals is 'oo' and where removed 3 vowels. But it should be 'o' and 4 vowels removed. Another example with error is 'Estaa e umaa string coom duuuplicadoos', I am getting ' Esta e uma string com duplcdos ' and 8 vowels removed.
Note: This is a simple question so there isn't need to complicate. It only askes the consecutive duplicate vowels. The cases 'oOoO' -> 'oO' ,'abAb'->'abAb','abab' -> 'ab','aba'-> 'aba',... are in another chapter XD.
int Vogais(char *s) {
if (*s == 'A' || *s == 'a' || *s == 'E' || *s == 'e'
|| *s == 'I' || *s == 'i' || *s == 'O' || *s == 'o'
|| *s == 'U' || *s == 'u') return 1;
return 0;
}
int retiraVogaisRep(char *s) {
int res = 0;
for (int i = 0; i < strlen(s); i++) {
for (int j = i + 1; s[j] != '\0'; j++) {
if (s[i] == s[j] && Vogais(&s[j]) == 1) {
res++;
for (int k = j; s[k] != '\0'; k++) {
s[k] = s[k + 1];
}
}
}
}
return res;
}
int main() {
char s[38];
printf("Digite uma String:\n");
scanf("%[^\n]", s);
int res = retiraVogaisRep(s);
printf("A String sem duplicados fica assim ' %s ' e foram retiradas %d vogais.\n", s, res);
return 0;
}
Your code is too complicated: there is no need for nested loops for this task and you do not set the null terminator when shortening the string.
Here is a simpler version:
#include <stdio.h>
#include <string.h>
int retiraVogaisRep(char *s) {
int i, j; // use 2 running indices
char c, last = 0;
for (i = j = 0; (c = s[i]) != '\0'; i++) {
if (c != last || !strchr("aeiouAEIOU", c))
s[j++] = last = c;
}
s[j] = '\0'; // set the null terminator
return i - j; // return the number of bytes removed
}
int main() {
char s[100];
printf("Digite uma String:\n");
// read the user input safely with `fgets()`
if (!fgets(s, sizeof s, stdin))
return 1;
// strip the trailing newline if any
s[strcspn(s, "\n")] = '\0';
// remove duplicate consecutive vowels
int res = retiraVogaisRep(s);
printf("A String sem duplicados fica assim ' %s ' e foram retiradas %d vogais.\n", s, res);
return 0;
}
The question tag is C, but I will not post the actual code here.
The pseudocode:
function is_vowel(int c) {...}
start loop c = <src>
if next_char is past the last char then quit loop;
if is_vowel(c) and c == next_char and is_vowel(next_char)
then continue;
else
copy c to <dst>
You should elaborate on this, as the above is possibly having small issues. Nevertheless, I think this answer is somewhat shorter and gives an insight.
Update
The above is definitly have an issue, in that the next char does not copied to the output. The mistake is easy to correct, so I will leave it up to OP.
Update
Edited above code to indicate that OP wants to remove only identical duplicates. So, the case of a charcter is important.
Rather than a triple nested loop, consider a single walk down the string, looking for repeats.
#include <stdio.h>
#include <ctype.h>
int Vogais(unsigned char s) {
if (s == 'A' || s == 'a' || s == 'E' || s == 'e'
|| s == 'I' || s == 'i' || s == 'O' || s == 'o'
|| s == 'U' || s == 'u') return 1;
return 0;
}
int retiraVogaisRep(char *s) {
unsigned char *us = (unsigned char *) s;
unsigned char *dest = us;
int res = 0;
int prior = EOF;
while (*us) {
while (toupper(*us) == prior) {
us++;
res++;
}
prior = Vogais(*us) ? toupper(*us) : EOF;
*dest++ = *us++;
}
*dest = '\0';
return res;
}
int main() {
char buf[100] = "OoFreedaa";
printf("%d\t", retiraVogaisRep(buf));
printf("<%s>\n", buf);
return 0;
}
Output
3 <OFreda>
Remove consecutive duplicate vowels
You should use tolower function from ctype.h to check for vowels, that include the letter 'y', see below working code:
You can store previous character in prev and compare it to the current character, as you are case insensitive you store the tolower version.
#include <string.h>
#include <stdio.h>
#include <ctype.h>
int Vogais(char c){
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y') ;
}
int retiraVogaisRep (unsigned char *s){
if (*s == NULL)
return 0;
unsigned char t[256];
memset(t, 0, sizeof(t));
int res = 0;
int j = 0;
t[0] = s[0];
char prev = tolower(s[0]);
int len = strlen(s);
for (int i = 1; i < len; i++) {
char c = tolower(s[i]);
if (Vogais(c) && c == prev)
++res;
else
t[j++] = s[i];
prev = c;
}
memcpy(s, t, sizeof(t));
return res;
}
int main(){
char s[256];
printf("Digite uma String:\n");
scanf("%255[^\n]", s);
int res = retiraVogaisRep(s);
printf("Da String ' %s ' podem ser retiradas %d vogais.\n", s,res);
return 0;
}
Retaining the uppercase, using the Kernighan-copy
#include <stdio.h>
#include <string.h>
#include <ctype.h>
size_t remove_duplicate_vowels(char *str)
{
int old,new;
size_t dst,src;
old = 0;
for(dst=src=0; str[dst] = str[src]; old=new, src++ ) {
new = toupper( str[dst] );
if ( !strchr( "AEIOU", new )) { // Not a vowel
dst++; continue;
}
if ( new != old ) { // Not a repetition
dst++; continue;
}
}
return src - dst;
}
int main(int argc, char **argv)
{
char test[] = "Aaa bbBb CccCC d eEeee!";
char *arg;
size_t ret;
arg = argv[1] ? argv[1] : test;
ret = remove_duplicate_vowels(arg);
fprintf(stderr, "[%zu]: %s\n", ret, arg);
return 0;
}
The code below is meant to take an input string like My name is Smith and outputs
My
name
is
Smith
and also has to exclude things like: , . and space, just these three, but instead it outputs, I'm not allowed to use any thing like strlen or strtok
My
y
name
ame
me
e
is
s
Smith
mith
ith
th
h
I've searched for the error everywhere in the code and I can't seem to figure it out
int main()
{
int wordSize = 0;
char str[81];
char* ptr_to_word[81];
gets_s(str);
for (char* res_p = &(str[0]); *res_p != '\0'; res_p++) {
if ((*res_p != '.') || (*res_p != ',') || (*res_p != ' '))
{
ptr_to_word[wordSize] = res_p;
wordSize++;
}
}
if (wordSize == 0)
{
printf("no solution");
}
else
{
for (int i = 0; i < wordSize; i)
{
char* a = ptr_to_word[i];
while ((*a != '.') && (*a != ',') && (*a != ' ') && (*a != '\0'))
{
printf("%c", *a);
a++;
}
printf("\n");
}
}
return 0;
}
In the condition of the if statement within this loop
for (char* res_p = &(str[0]); *res_p != '\0'; res_p++) {
if ((*res_p != '.') || (*res_p != ',') || (*res_p != ' '))
{
ptr_to_word[wordSize] = res_p;
wordSize++;
}
}
you have to use the logical AND operator instead of the logical OR operator like
if ((*res_p != '.') && (*res_p != ',') && (*res_p != ' '))
Nevertheless the loop in any case is wrong because the variable wordSize does not count words but counts each character that is not equal to the characters listed in the if statement.
To output separate words there is no need to declare an array of pointers to starts of words. You can output each word as soon as its start is found.
Here is a very simple demonstrative program.
#include <stdio.h>
int main(void)
{
enum { N = 81 };
char s[N];
fgets( s, N, stdin );
for ( const char *p = s; *p; )
{
int wordSize = 0;
while ( *p && *p != '.' && *p != ',' && *p != ' ' && *p != '\t' && *p != '\n' )
{
++wordSize;
++p;
}
if ( wordSize )
{
printf( "%.*s\n", wordSize, p - wordSize );
}
else
{
++p;
}
}
return 0;
}
If to input "My name is Smith" then the program output might look like
My
name
is
Smith
I appended the list of delimiters with the tab character '\t' and the new line character '\n' that can be inserted in the input string by the function fgets.
First of all, this condition
if ((*res_p != '.') || (*res_p != ',') || (*res_p != ' ')
will always be true, think about it, *res_p is always not '.' OR not ','. However, if you change the operator to && your code will still produce the same result.
The first loop with || operator writes a pointer to every character in your input string to the array ptr_to_word, and ' 's and '.'s are not printed only because of a condition in the second loop.
If you change the operator to && like so,
if ((*res_p != '.') && (*res_p != ',') && (*res_p != ' ')
you will write all the pointers, except for the '.', ',' and ' ', into the array, e.g. ptr_to_word[0] will point to 'My name is Smith', ptr_to_word[1] to 'y name is Smith', etc.
I have made a few changes to your code so that it would work as intended.
void split_str(char *str)
{
int wordSize = 0;
char *ptr_to_word[81];
char *res_p = &(str[0]);
int i = 0;
for (; *res_p != '\0'; res_p++) {
if ((*res_p != '.') && (*res_p != ',') && (*res_p != ' '))
{
wordSize++;
}
else
{
ptr_to_word[i] = res_p - wordSize;
wordSize = 0;
i++;
}
}
ptr_to_word[i] = res_p - wordSize;
ptr_to_word[i + 1] = NULL;
if (i == 0)
{
printf("no solution\n");
}
else
{
for (int i = 0; ptr_to_word[i]; i++)
{
char* a = ptr_to_word[i];
while ((*a != '.') && (*a != ',') && (*a != ' ') && (*a != '\0'))
{
printf("%c", *a);
a++;
}
printf("\n");
}
}
}
int main() {
split_str("My name is Smith\n");
}
This way you are writing a new value to the pointer array only when dot, comma or a space is encountered. For all other chars, you just do wordSize++ to keep track of the length of the word. I used pointer arithmetic to move back to the start of the word (ptr_to_word[i] = res_p - wordSize;).
I have tried to make only minimal changes to your code, just enough to make it work. There are still things I would change to make it better, e.g. the first loop finishes when the '\0' is encountered. Most likely, the last word finishes with a '\0', not a '.' or a ' '. Thus, it won't be written to the ptr_to_word, and I had to manually write it after the loop. Also, you don't even need two loops, you can use the same pointer. arithmetic to output the word as soon as it is found. So I'd advise you to do. a self-code-review, and optimize it further.
Good luck!
I was writing a code that takes a sentence and reverses it, as an exercise. Here's what I wrote:
#include <stdio.h>
int main(void)
{
char a, sentence[100], sign;
char *c = sentence;
printf("Enter a sentence: ");
while ( (a = getchar()) != '\n' )
{
if ( a == '?' || a == '!' || a == '.')
{
sign = a;
break;
}
*c = a;
c++;
}
for (char *d = c; d >= sentence; d--)
{
if ( (d == sentence) && (*d != ' ') )
{
for (char *a = d; a < d + 99; a++)
{
if ( (*a == ' ') || (*a == '\n')) //code isn't reading the \n
{
break;
}
else
printf("%c", *a);
}
}
if ( (*d == ' ') && (d != c) && (d != sentence + 99) )
{
for (char *a = d+1; a <= c; a++)
{
if ( (*a == ' ') || (a == c))
{
printf(" ");
break;
}
else
printf("%c", *a);
}
}
}
printf("%c\n", sign);
return 0;
}
It works fine when I input a sentence with spaces in it:
Enter a sentence: This is a sentence
sentence a is This
However if I input a string with no spaces, like this:
Enter a sentence: Thisisasentence
I get an output with what was originally entered ('Thisisasentence'), followed by a lot of gibberish output. From what I understand, this is because the code doesn't go into the if ( (*a == ' ') || (*a == '\n') condition.
Why isn't the compiler reading the '\n'
The program works with a couple of changes.
In the while add *c = '\0'; after c++; to terminate the string.
Check for a == '\0' instead of '\n' as the while excludes the '\n'.
Added a check at the end of the while to make sure no more than 99 characters are allowed.
#include <stdio.h>
int main(void)
{
char a, sentence[100], sign;
char *c = sentence;
printf("Enter a sentence: ");
while ( (a = getchar()) != '\n' )
{
if ( a == '?' || a == '!' || a == '.')
{
sign = a;
break;
}
*c = a;
c++;
*c = '\0';//terminate
if ( c - sentence >= 99) {//make sure not too many characters
break;
}
}
for (char *d = c; d >= sentence; d--)//start at c and work back to sentence[0]
{
if ( (d == sentence) && (*d != ' ') )
{
for (char *a = d; !( *a == ' ' || *a == '\0'); a++)
{
printf("%c", *a);
}
}
if ( (*d == ' ') && (d != c) && (d != sentence + 99) )
{
for (char *a = d+1; a <= c; a++)
{
if ( (*a == ' ') || (a == c))
{
printf(" ");
break;
}
else
printf("%c", *a);
}
}
}
printf("%c\n", sign);
return 0;
}
It is probably best to split to work into two functions, one for reading a line of text and one for reversing it:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void reverse_string(char *str) {
/* skip null */
if (str == 0) {
return;
}
/* skip empty string */
if (*str == 0) {
return;
}
/* get range */
char *start = str;
char *end = start + strlen(str) - 1; /* -1 for \0 */
char temp;
/* reverse */
while (end > start) {
/* swap */
temp = *start;
*start = *end;
*end = temp;
/* move */
++start;
--end;
}
}
char *read(void) {
char *line = malloc(100), *linep = line;
size_t lenmax = 100, len = lenmax;
int c;
if (line == NULL)
return NULL;
for (;;) {
c = fgetc(stdin);
if (c == EOF)
break;
if (--len == 0) {
len = lenmax;
char *linen = realloc(linep, lenmax *= 2);
if (linen == NULL) {
free(linep);
return NULL;
}
line = linen + (line - linep);
linep = linen;
}
if ((*line++ = c) == '\n')
break;
}
*line = '\0';
return linep;
}
int main(void) {
printf("Enter a sentence:");
char *sentence = read();
reverse_string(sentence);
printf(sentence);
return 0;
}
Test 1
Enter a sentence:this is a sentence
ecnetnes a si siht
Test 2
Enter a sentence:thisisasentence
ecnetnesasisiht
Before reading this question please note that my question pertains to a school assignment. For this assignment the only function we are allowed to use is malloc(). Everything else must be done without the use of other libraries.
I'm calling a function ft_split_whitespaces. This function takes a string as input and "splits" it into words. Words are separated spaces, tabs and line breaks.
#include <stdio.h>
char **ft_split_whitespaces(char *str);
int main(void)
{
char *str = "what is";
char **test = ft_split_whitespaces(str);
}
With respect to the example above the result at each index should be
test[0] = "what"
test[1] = "is"
test[2] = NULL
However, I am only able to print the results of test[0]. All other indices do not get printed to display. Heres an example of some code that I assume should print the results of my function.
int i = 0;
while(test[i] != NULL)
{
printf("%s", test[i]);
i++;
}
When this portion of code is ran, only test[0] is printed to the output. I've been sitting here trying to debug my code for hours. If anyone has some spare time and doesn't mind looking over my code, I'd appreciate it tremendously. I have a feeling it may be an issue with how I'm using malloc, but I still cant figure it out.
#include <stdlib.h>
#include <stdio.h>
int count_whitespaces(char *str)
{
int space_count;
int i;
space_count = 0;
i = 0;
while(str[i] != '\0')
{
if(str[i] == ' ' || str[i] == 9 || str[i] == '\n')
{
if(str[i+1] != ' ' && str[i+1] != 9 && str[i+1] != '\n')
space_count++;
}
i++;
}
return (space_count);
}
int check_whitespace(char c)
{
if (c == ' ' || c == 9 || c == '\n' || c == '\0')
{
return (1);
}
else
return(0);
}
int count_characters(char *str, int i)
{
int char_count;
char_count = 0;
while(str[i])
{
if(str[i+1] != ' ' && str[i+1] != 9 && str[i+1] != '\n')
char_count++;
else
break;
i++;
}
return (char_count);
}
char **ft_split_whitespaces(char *str)
{
int i;
int j;
int k;
char **word;
int space;
i = 0;
j = 0;
k = 0;
word = (char**)malloc(sizeof(char*)*(count_whitespaces(str) + 2));
while(str[i] != '\0')
{
if (check_whitespace(str[i]) == 1)
i++;
else
{
if((word[j] = malloc(sizeof(char) * (count_characters(str, i) + 1))) == NULL)
return (NULL);
while (check_whitespace(str[i]) == 0)
{
word[j][k] = str[i];
i++;
k++;
}
j++;
}
}
j++;
word[j] = NULL;
j = 0
return word;
}
You forgot to reset k. The outer while loop in ft_split_whitespaces should look like that
while (str[i] != '\0') {
if (check_whitespace(str[i]) == 1){
i++;
}
else {
if ((word[j] =
malloc(sizeof(char) * (count_characters(str, i) + 1))) == NULL){
return (NULL);
}
while (check_whitespace(str[i]) == 0) {
word[j][k] = str[i];
i++;
k++;
}
word[j][k] = '\0';
j++;
k = 0; // reset k
}
}
So I actually figured out what was going wrong with my code as I finished typing this question (thanks stack overflow!). I decided to post it anyways, because I thought it might be a good learning experience for coding newbies such as myself.
This is where my issue was occurring.
word = (char**)malloc(sizeof(char*)*(count_whitespaces(str) + 2));
while(str[i] != '\0')
{
if (check_whitespace(str[i]) == 1)
i++;
else
{
if((word[j] = malloc(sizeof(char) * (count_characters(str, i) + 1))) == NULL)
return (NULL);
while (check_whitespace(str[i]) == 0)
{
word[j][k] = str[i];
i++;
k++;
}
j++;
}
}
I malloc'd my char **word outside of the while loop using the following code
word = (char**)malloc(sizeof(char*)*(count_whitespaces(str) + 2));
And then within the actual while loop I malloc'd it again using
word = (char**)malloc(sizeof(char*)*(count_whitespaces(str) + 2));
Using malloc multiple times on the same variable was causing all sorts of weird issues. So within the while loop I ended up using a new variable I declared as char *words. Here is that portion of the while loop with the correct code.
word = (char**)malloc(sizeof(char*)*(count_whitespaces(str) + 2));
while(str[i] != '\0')
{
if (check_whitespace(str[i]) == 1)
i++;
else
{
words = malloc(sizeof(char) * (count_characters(str, i) + 1));
k = 0;
while (check_whitespace(str[i]) == 0)
{
words[k] = str[i];
i++;
k++;
}
words[k] = '\0';
word[j] = words;
j++;
}
}