In this code I have got a string input- "WUBABCWUBNAWBWUB".
here i need to remove the word "WUB" and print the remaining.Example: "ABC NAWB";
i have almost solved it but the problem is when i give the input(given above) I get a garbage value at the end.It shows: "ABC NAWB~#".I cant understand whats wrong with the code,please help me to remove those garbage values.
#include <stdio.h>
#include <string.h>
int main() {
char str[201], original[201];
int cnt = 0, i, j = 0;
int len = strlen(str);
gets(str);
for(i = 0; i < len-3; i++) {
if(str[i] == 'W' && str[i+1] == 'U' && str[i+2] == 'B' && i != len) {
if(i != 0 && i != len-3) {
original[cnt] = ' '; //here i changed "WUB" into a blank line
j++;
cnt++;
}
i = i+2;
} else {
original[j] = str[i];
cnt++;
j++;
}
}
printf("%c %c\n", original[j], original[j+1]);
printf("%s", original);
printf("\n\nj=%d,i=%d,cnt=%d", j, i, cnt);
}
A few modifications:
I have added a '\0' the end at the new string
I have modified the code such that it works even if the end is not equal to WUB (maybe useless modification)
I have removed the redundant j index
I have replaced the gets function with the more secure fgets
#include<stdio.h>
#include<string.h>
int main()
{
char str[201],original[201];
fgets(str, 200, stdin);
int cnt=0,i, len=strlen(str);
for(i = 0; i <= len-3; i++) {
if(str[i]=='W' && str[i+1]=='U' && str[i+2]=='B' && i!=len) {
if(i!=0 && i!=len-3) {
original[cnt++] = ' '; //here i changed "WUB" into a blank line
}
i = i+2; // to jump over the "WUB" word
} else {
original[cnt++] = str[i];
}
}
for (int j = i; j < len; j++) { // to deal with the case the string doesn't terminate with "WUB"
original[cnt++] = str[j];
}
original[cnt++] = '\0';
//printf("%c %c\n",original[cnt],original[cnt+1]);
printf("%s",original);
//printf("\n\n,i=%d,cnt=%d",i,cnt);
}
Strings are actually a one-dimensional array of characters terminated by a null character '\0'. so in your program original is a character array and once the values are assigned to it, at last '\0' should be there so adding just one line of code may help you get correct output.
original[j]='\0';
thanks guys,i've solved the problem.The problem was solved after giving
original[j]='/0';
after the loop.I also used the cnt integer to avoid blanks more than once.Here is my new code.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char str[201],original[201];
fgets(str,201,stdin);
int cnt=0,i,j=0,len=strlen(str);
for(i=0;str[i]!='\0';i++){
if(str[i]=='W' && str[i+1]=='U' && str[i+2]=='B')
{
if(i!=0 && i!=len-3&&cnt==0&&j!=0)
{
original[j] = ' ';
cnt++;
j++;
}
i=i+2;
}
else
{
original[j] = str[i];
cnt=0;
j++;
}
}
original[j]='\0';
printf("%s",original);
}
Related
I tried modifying this code to print
no solution
if there is no input by user. That is, if I run the program and simply press enter it should print no solution. I added the code that's meant to do that to check if the string length is 0 then print but it doesn't work
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100];
char newString[10][10];
int i, j, ctr;
fgets(str1, sizeof str1, stdin);
j = 0; ctr = 0;
if (strlen(str1) == 0) {
printf_s("no solution");
}
else
for (i = 0; i <= (strlen(str1)); i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if (str1[i] == ' ' || str1[i] == '\0')
{
newString[ctr][j] = '\0';
ctr++; //for next word
j = 0; //for next word, init index to 0
}
else if (str1[i] == '.' || str1[i] == ',')
{
newString[ctr][j] = '\0';
ctr--; //for next word
j = - 1;
}
else
{
newString[ctr][j] = str1[i];
j++;
}
}
printf("\n\n");
for (i = 0; i < ctr; i++)
printf(" %s\n", newString[i]);
return 0;
}
fgets() will add a new line to your string (see this link for more information) which means when you simply press enter your string length(since your string includes \n) is 1 , you should say:
if (strlen(str1) == 1) {
printf_s("no solution");
// it's better to add a return 0; here if you don't want to continue the program
}
or use this instead:
if (!strcmp(str1,"\n")) {
printf_s("no solution");
}
So my program should get input from an user and store it in an array. After that if the input string includes three 'a's in a row it should be replaced with a single '*'. However I can't seem to get it right. It only replaces the first a with a *. I tried to replace the following 2 a with a blank but the output looks funny.
For this exercise I have to use putchar() and getchar().
Thank you in advance.
#include <stdio.h>
char c;
char buffer[256];
int counter= 0;
int i;
int main()
{
while ((c = getchar()) != '\n') {
buffer[counter] =c;
counter++;
if (counter >255) {
break;
}
}
for(i=0; i<256; i++) {
if(buffer[i]== 'a'&&buffer[i+1]=='a'&&buffer[i+2]=='a')
{
buffer[i]= '*';
buffer[i+1]=' ';
buffer[i+2]=' ';
}
putchar(buffer[i]);
}
putchar('\n');
return 0;
}
So my program should get input from an user and store it in an array.
After that if the input string includes three 'a's in a row it should
be replaced with a single '*'. However I can't seem to get it right.
You almost got it! Just move index by 2 to and continue.
#include <stdio.h>
char c;
char buffer[256];
int counter= 0;
int i;
int main(void)
{
while ((c = getchar()) != '\n') {
buffer[counter] =c;
counter++;
if (counter >= 255) {
break;
}
}
buffer[counter] ='\0';
for(i=0; i<256; i++) {
if(buffer[i]== 'a'&&buffer[i+1]=='a'&&buffer[i+2]=='a')
{
buffer[i]= '*';
putchar(buffer[i]);
i = i + 2;
continue;
}
putchar(buffer[i]);
}
putchar('\n');
return 0;
}
Test:
123aaa456aaa78
123*456*78
In string you must assign a end of character at the end and that is call null character \0 or just a numeric 0. Correct your code like below:-
while ((c = getchar()) != '\n') {
buffer[counter] =c;
counter++;
if (counter >=255) {
break;
}
}
buffer[counter] ='\0';// or buffer[counter] =0;
To avoid side effect in a string array always set all its value with 0 first:-
char buffer[256];
memset(buffer, 0, sizeof(buffer));
If you want to change the number of characters, you will need to create a different buffer to copy the output to.
If you really just want to output to the console, you could just write every character until you hit your matching string.
#include <stdio.h>
char c;
char buffer[256];
char output[256];
int counter= 0;
int i, j;
int main()
{
while ((c = getchar()) != '\n') {
buffer[counter] = c;
counter++;
if (counter >255) {
break;
}
}
buffer[counter] = 0;
for(i=0, j=0; i<256; i++, j++) {
if(buffer[i] == 'a' && buffer[i+1] == 'a'&& buffer[i+2] == 'a')
{
output[j]= '*';
i += 2;
}
else
output[j] = buffer[i];
putchar(output[j]);
}
putchar('\n');
return 0;
}
There are multiple problems in your code:
there is no reason to make all these variables global. Declare them locally in the body of the main function.
use int for the type of c as the return value of getchar() does not fit in a char.
you do not check for EOF.
your test for buffer overflow is off by one.
you do not null terminate the string in buffer. You probably make buffer global so it is initialized to all bits 0, but a better solution is to set the null terminator explicitly after the reading loop.
to replace a sequence of 3 characters with a single one, you need to copy the rest of the string.
You can use a simple method referred as the 2 finger approach: you use 2 different index variables into the same array, one for reading, one for writing.
Here is how it works:
#include <stdio.h>
int main() {
char buffer[256];
int c;
size_t i, j, counter;
for (counter = 0; counter < sizeof(buffer) - 1; counter++) {
if ((c = getchar()) == EOF || c == '\n')
break;
buffer[counter] = c;
}
buffer[counter] = '\0';
for (i = j = 0; i < counter; i++, j++) {
if (buffer[i] == 'a' && buffer[i + 1] == 'a' && buffer[i + 2] == 'a') {
buffer[j] = '*';
i += 2;
} else {
buffer[j] = buffer[i];
}
}
buffer[j] = '\0'; /* set the null terminator, the string may be shorter */
printf("modified string: %s\n", buffer);
return 0;
}
I am new to C so please forgive my misunderstandings. I am trying to write a simple program that takes a users character input, mutates it, and prints it out in "piglatin"... where the first letter of a word is moved to the end of the word and then an "ay" is appended to the end of the word. Example-> the word "like" becomes ... "ikelay". Here is my program...
//pig latin
#include <stdio.h>
#define MAX 1000
void pigify(char chars[], int cnt);
void sortWords(char stream[], int total);
void clearWord(char word[], int j);
int main(){
int c, i;
char allChars[MAX];
i = 0;
while((c = getchar()) != EOF){
allChars[i] = c;
++i;
}
allChars[i] = '\0';
sortWords(allChars, i);
return 0;
}
/////////////////
/////////////////
void sortWords(char stream[], int total){
int i, j, start, end, m;
char words[total];
clearWord(words, total);
i = j = end = m = 0;
while(stream[i] != '\0'){
if(stream[i] != '\n' && stream[i] != '\t' && stream[i] != ' '){
++i;
++j;
} else if (j > 2){
end = i;
for(start = i-j; start <= end; ++start){
words[m] = stream[start];
++m;
}
pigify(words, m);
clearWord(words, m);
j = m = 0;
}
}
}
/////////////////
/////////////////
void clearWord(char word[], int i){
int j;
for (j = 0; j <= i; ++j){
word[j] = '\0';
}
}
/////////////////
/////////////////
void pigify(char alls[], int cnt){
int j;
char pchars[cnt+3];
j = 0;
while(alls[j] != '\0'){
pchars[j] = alls[j];
++j;
}
if(alls[0] != 'a' && alls[0] != 'e' && alls[0] != 'i' && alls[0] != 'o' && alls[0] != 'u'){
pchars[cnt] = alls[0];
pchars[cnt+1] = 'a';
pchars[cnt+2] = 'y';
pchars[cnt+3] = '\0';
pchars[0] = ' ';
}
printf("\npost pigification --> %s\n", pchars);
}
I have been on it for a long time and I can't find where i've made a mistake. I do not care so much about the program, I don't need to convert input to "piglatin" but I would really love to know what I have done wrong!!! Help, advice, and/or pointers would be awesome! thank you
Writing outside array bounds. Use <
char words[total];
clearWord(words, total);
void clearWord(char word[], int i){
int j;
// for (j = 0; j <= i; ++j){
for (j = 0; j < i; ++j){
word[j] = '\0';
}
}
May have other problems too
Replace this line:
while((c = getchar()) != EOF){
allChars[i] = c;
++i;
}
With this:
while ((allChars[i] = getchar()) != '\n')
i++;
Otherwise, every time you press enter, the loop starts over. Maybe someone else can explain that, but the above code will let your code do what you want it to.
In the future, a function such as fgets() may be more suitable for your needs, as you don't have to worry about checking for EOF and such - you just have to strip the newline at the end in that case.
With help form #chux and after using some more print statements to find out what is going on, I realized that in the function sortWords the variable i was not being incremented for the case in which a space '' '' character or a new line or tab character ''\n'' and ''\t'' was reached. After changing the function to this ...
void sortWords(char stream[], int total){
int i, j, start, end, m;
char words[total];
clearWord(words, total);
i = j = end = m = 0;
while(stream[i] != '\0'){
if(stream[i] != '\n' && stream[i] != '\t' && stream[i] != ' '){
++i;
++j;
} else if (j > 2){
end = i;
for(start = i-j; start <= end; ++start){
words[m] = stream[start];
++m;
}
pigify(words, m);
clearWord(words, m);
j = m = 0;
++i;
}
}
}
The program works at least somewhat more as expected. The bugs i set out to solve with this question are fixed at least. Still not perfect but i think this was a poorly asked question on my part and should be ended
I'm writing a program to count spaces and vowels and it didnĀ“t work, I think I did an infinite loop.I'll show you my code:
int contar_p(char a[100]) {
int i = 0, spaces = 1;
while (a[i] != '\0' && i < 100) {
if (a[i] == ' ') {
spaces += 1;
i++;
}
}
return spaces;
}
int contar_v(char b[100]) {
int i = 0, counter = 0;
while (b[i] != '\0' && i < 100) {
if (b[i] == 'a' || b[i] == 'e' || b[i] == 'i' || b[i] == 'o' || b[i] == 'u') {
counter += 1;
}
i++;
}
return counter;
}
int main(void){
char phrase[100];
int words = 0, vowels = 0;
printf("write a phrase ");
gets(phrase);
palabras = contar_p(phrase);
vocales = contar_v(phrase);
printf("%d\n", words);
printf("%d", vowels);
return 0;
}
The loop
while (a[i]!='\0'&&i<100){
if(a[i]==' '){
spaces+=1;
i++;
}
}
is an infinite loop. Place i++ outside the if. Change it to
while (a[i]!='\0'){ // No need of condition i < 100
if(a[i]==' '){
spaces+=1;
}
i++;
}
Maybe another approach will help you to understand things easier, i'm mean you do know that there are A,E,I,O,U also and not only a,e,i,o,u. You should never use gets instead use fgets, anyway take a look at the following program:
#include <stdlib.h>
#include <stdio.h>
void countVowels(char* array){
int i,j,v;
i=0;
int count = 0;
char vowel[]={'a','e','i','o','u','A','E','I','O','U'};
while(array[i]!='\0'){
for(v=0;v<10;v++){
if (array[i]==vowel[v]){
j=i;
while(array[j]!='\0'){
array[j]=array[j+1];
j++;
}
count++;
i--;
break;
}
}
i++;
}
printf("Found %d Vowels\n",count);
}
void contar_p(char a[100]) {
int i = 0, spaces = 0;
for(i=0;a[i]!='\0';i++){
if(a[i]==' ')
spaces++;
}
printf("Found %d Spaces\n",spaces);
}
int main(void){
char a[]="aa bb EOU cc ii";
countVowels(a);
contar_p(a);
return 0;
}
Output:
Found 7 Vowels
Found 4 Spaces
I'm trying to determine if a phrase is a palindrome (a word that is the same from left to rigth) or not but i can't make it work. What's wrong?, i can't use pointers or recursion or string type variables
#include <stdio.h>
#include <string.h>
int main()
{
int i,j = 0,length;
char space = ' ';
char phrase [80],phrase2[80],phrase3[80];
printf("Give me the phrase: ");
gets(phrase);
length = strlen(phrase);
for(i =0; i <= length - 1; i++)
{
if(phrase[i] != space) //Makes the phrase without spaces
{
phrase2[i] = phrase[i];
j++;
}
}
for(i = length -1; i >= 0;i--)
{
if(phrase[i] != space) //Makes the phrase backwards an without spaces
{
phrase3[j] = phrase[i];
j++;
}
}
length = strlen(phrase2);
for(i =0; i <= length -1;i++) //Compare the phrases to know if they are the same
{
if(phrase2[i] != phrase3[i])
{
printf("It's not a palindrome\n");
return 0;
}
}
printf("It's a palindrome\n");
return 0;
}
Try this:
for(i =0, j=0; i <= length - 1; i++)
{
if(phrase[i] != space) //Makes the phrase without spaces
{
phrase2[j] = phrase[i];
j++;
}
}
for(i = length -1, j = 0; i >= 0;i--)
{
if(phrase[i] != space) //Makes the phrase backwards an without spaces
{
phrase3[j] = phrase[i];
j++;
}
}
length = j;
Update
In response to Praetorian's post here's the code to do it without copying the string.
#include <stdio.h>
#include <string.h>
int main()
{
int i, j, length;
char space = ' ';
char phrase[80];
printf("Give me the phrase: ");
gets(phrase);
length = strlen(phrase);
for( i = 0, j = length - 1; i < j; i++, j-- ) {
while (phrase[i] == space) i++;
while (phrase[j] == space) j--;
if( phrase[i] != phrase[j] ) {
printf("It's not a palindrome\n");
return 0;
}
}
printf("It's a palindrome\n");
return 0;
}
Before the 2nd loop you want to set j=0. It should work after that.
PS: If you debugged by printing out your three strings, you would've figured it out in a matter of minutes. When you don't know what goes wrong, print out the values of variables at intermediate steps, so you know where your problem occurs and what it is.
Your question has already been answered by others but I'm posting this code to show that it is not necessary to make the phrase3 copy to hold the reversed string.
#include <stdio.h>
#include <string.h>
int main()
{
int i, j, length, halfLength;
char space = ' ';
char phrase1[80], phrase2[80];
printf("Give me the phrase: ");
gets(phrase1);
length = strlen(phrase1);
for( i = 0, j = 0; i <= length; ++i ) {
if( phrase1[i] != space ) { //Makes the phrase1 without spaces
phrase2[j++] = phrase1[i];
}
}
length = strlen(phrase2);
halfLength = length / 2;
for( i = 0, j = length - 1; i < halfLength; ++i, --j ) {
if( phrase2[i] != phrase2[j] ) {
printf("It's not a palindrome\n");
return 0;
}
}
printf("It's a palindrome\n");
return 0;
}
This is what I came up with:
#include <stdio.h>
void main() {
char a[50],b[50];
int i=0,j,ele,test=0,x;
while((a[i]=getchar())!='\n') {
if(a[i]!=' ' && a[i]!=',') //do not read whitespaces and commas(for palindromes like "Ah, Satan sees Natasha")
i++;
}
a[i]='\0';
ele=strlen(a);
// Convert string to lower case (like reverse of Ava is avA and they're not equal)
for(i=0; i<ele; i++)
if(a[i]>='A'&&a[i]<='Z')
a[i] = a[i]+('a'-'A');
x = ele-1;
for(j=0; j<ele; j++) {
b[j] = a[x];
x--;
}
for(i=0; i<ele; i++)
if(a[i]==b[i])
test++;
if(test==ele)
printf("You entered a palindrome!");
else
printf("That's not a palindrome!");
}
Probably not the best way for palindromes, but I'm proud I made this on my own took me 1 hour :( lol
Why not use a std::stack? You will need two loops, each iterating the length of the input string. In the first loop, go through the input string once, pushing each character ont the stack. In the second loop, pop a character off the stack and compare it with the character at the index. If you get a mismatch before the loop ends, you don't have a palindrome. The nice thing with this is that you don't have to worry about the even/odd length corner-case. It will just work.
(If you are so inclined, you can use one stack (LIFO) and one queue (FIFO) but that doesn't substantially change the algorithm).
Here's the implementation:
bool palindrome(const char *s)
{
std::stack<char> p; // be sure to #include <stack>
for(int i = 0; s[i] != 0; i++)
p.push(s[i]);
for(int i = 0; s[i] != 0; i++)
{
if(p.top() != s[i])
return false; // not a palindrome!
p.pop();
}
return true;
}
Skipping spaces is left as an exercise to the reader ;)