can anyone say me what is the mistake here. I used two dimensional array here.
#include<stdio.h>
#include<string.h>
int main()
{
char a[100], b[30][30], c[20], d[20];
int i, j=0, k, count=0;
int e[30];
printf("enter a string: ");
gets(a);
printf("enter the word which has to be replaced: ");
gets(c);
printf("enter the word with which it has to be replaced: ");
gets(d);
for(i=0,k=0, e[i]=0; i<strlen(a); i++, k++)
{
if(a[i]==' ')
{
k=0;
j++;
count++;
}
else
{
b[j][k]=a[i];
e[i]++;
}
}
for(i=0; i<j; i++)
{
if(word(b[i], c)==0)
{
for(k=0; k<strlen(d); k++)
{
b[i][k]=d[k];
}
}
}
for(i=0; i<count; i++)
{
for(j=0; j<e[i]; j++)
{
printf("%c", b[i][j]);
}
printf(" ");
}
}
int word(char *a, char *c)
{
int i;
if(strlen(a)==strlen(c))
{
for(i=0; i<strlen(a); i++)
{
if(a[i]!=c[i])
{
return 1;
}
}
}
else
return 2;
return 0;
}
I want the output to be like the below.
For example:
enter a string: vicky is a good boy
enter the word which has to be replaced: good
enter the word with which it has to be replaced: bad
vicky is a bad boy
I mean I want to replace only that particular word, as many times as it appears in the string such as here, the word good. Can anyone help me identify the mistake or help me find another way.
You should not use gets, it's dangerous: Why is the gets function so dangerous that it should not be used?.
You should use fgets to read from stdin instead.
Int the word function, you compare length of two string using strlen funciton:
if(strlen(a)==strlen(c))
But in the main function, you call it as:
if(word(b[i], c)==0)
b[i] is array of character, but you do not add null character \0 at the end of each word. So strlen will not work as you think.
In the code that you replace string c by d. You not update value of e array.
I think, e[i] should be:
e[i] = strlen(d);
I seem that you do not use some standard function for string, for example, very useful for your program.
strcmp to compare string and string.
strstr to find the word in the string.
If you search in google, you can have a ton of code for your case.
for example: program to Replace a word in a text by another given word
another: Replacing Words inside string in C
Related
I'm trying to find the repeating elements in the 2 strings. Here is what I have done.
int main()
{
int i, j;
char S[5];
char J[4];
printf("Enter the 1st string\n");
scanf("%s", &S);
printf("\nEnter the 2nd string\n");
scanf("%s",&J);
printf("\n1st string characters are %s", &S);
printf("\n2nd string characters are %s", &J);
for(i=0; i<5; i++)
{
for (j=0; j<3; j++)
{
if(J[j] == S[i])
{
printf("\n\nThe element is found and is at %c", *(&S[i]));
break;
}
else
{
printf("\nNo matching element found");
break;
}
}
}
return 0;
}
The output im getting is
Enter the 1st string
asdf
Enter the 2nd string
cfv
1st string characters are asdf
2nd string characters are cfv
The element is found and is at
No matching element found
No matching element found
No matching element found
No matching element found
No matching element found
Any idea why this might be happening? I'm a rookie in this. Any help is appreciated
i can make a few suggestions in your loop replace i<5 and j<3 to i<strlen(S) similarly j<strlen(J)
strlen is used to calculate string length.
and do not use break; otherwise it will skip the loop at first match . so try this
#include<stdio.h>
#include <string.h>
int main() {
int i, j;
char S[]="rat";
char J[]="fat";
printf("\n1st string characters are %s", &S);
printf("\n2nd string characters are %s", &J);
for(i=0; S[i] != '\0';; i++)
{
for (j=0; J[j] != '\0';; j++)
{
if(J[j] == S[i])
{
printf("\n\nThe element is found and is at %c", *(&S[i]));
}
else
{
printf("\nNo matching element found");
}
}
}
return 0;
}
click here to see the outputThe output is shown in a image.
sorry i was not having a c compiler in my system so used online one and may be thats why the location is not shown but yes it resolves your problem the matches are being detected.
I'm completely new to programming (1st term in uni) and I can't keep up with my lecturer. At the moment I'm stuck on this exercise (for much more time than I'm willing to admit). I've tried to find help on the internet (in this site and others as well), but I can't, since our lecturer has us use a very simple form of c. I'm not asking necessarily for a complete answer. I'd really appreaciate even some hints about where I'm on the wrong. I understand that it might be really simple for some, that the question might seem ignorant or stupid and I feel bad for not getting what's wrong, but I need to try to understand.
So, what I'm trying to do is use scanf and a do while loop so the user can input characters in an array. But I don't understand why the loop won't stop when the user presses ENTER. There's more to the code, but I'm trying to take it slowly, step by step. (I'm not allowed to use pointers and getchar etc).
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do
{
scanf("%c", &a[i]);
i=i+1;
}
while((i<=50) && (a[i-1]!='\0'));
for(i=0; i<50; i++)
printf("%c", a[i]);
}
There aren't any nul-terminated strings here, but only string arrays.
So, when pressing enter, a[i-1] is \n not \0 (scanf with %c as parameter doesn't nul-terminate the strings, and ENTER is just a non-nul character with code 10 AKA \n)
Then don't print the rest of the string because you'll get junk, just reuse i when printing the string back:
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do
{
scanf("%c", &a[i]);
i=i+1;
}
while((i<sizeof(a)) && (a[i-1]!='\n')); // \n not \0
int j;
for(j=0; j<i; j++) // stop at i
printf("%c", a[j]); // output is flushed when \n is printed
}
Also test with i<50 not i<=50 because a[50] is outside the array bounds (I've generalized to sizeof(a))
Here is another way you can do this.
#include <stdio.h>
// define Start
#define ARRAY_SIZE 50
// define End
// Function Prototypes Start
void array_reader(char array[]);
void array_printer(char array[]);
// Function Prototypes End
int main(void) {
char user_input[ARRAY_SIZE];
printf("Please enter some characters (50 max)!\n");
array_reader(user_input);
printf("Here is what you said:\n");
array_printer(user_input);
return 0;
}
// Scans in characters into an array. Stops scanning if
// 50 characters have been scanned in or if it reads a
// new line.
void array_reader(char array[]) {
scanf("%c", &array[0]);
int i = 0;
while (
(array[i] != '\n') &&
(i < ARRAY_SIZE)
) {
i++;
scanf("%c", &array[i]);
}
array[i + 1] = '\0';
}
// Prints out an array of characters until it reaches
// the null terminator
void array_printer(char array[]) {
int i = 0;
while (array[i] != '\0') {
printf("%c", array[i]);
i++;
}
}
You may try with this code:
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do {
scanf("%c", &a[i]);
i=i+1;
} while(i<50 && a[i-1] != '\n');
a[i] = 0;
for(i=0; a[i] != 0; i++)
printf("%c", a[i]);
}
The function scanf("%c", pointer) will read one character at a time and place it at the pointer location. You are looking for '\0', which is a valid string terminator, but the newline character you get when you press ENTER and that you should be looking for is '\n'.
Also, it is a good idea to terminate the string you have read by adding a '\0' at the end (really a zero). Then use it to stop printing or you may print the "rest" of the contents of an uninitialized char array.
int i,j,k;
char key[5], input[5], word[7], output[7];
printf("Enter key:\n");
fgets(input, 5, stdin);
printf("Enter word:\n");
fgets(word, 7, stdin);
//I am trying to store two
for (i = 0; i<7; i++) { //user-inputted arrays and then
for (j = 0; j<5; j++) { //do stuff with them. Fails before
if (word[i] == key[j]) { //I even get to the for loop.
output[i] = input[j];
}
}
}
Okay so basically this is the main portion of a program which is supposed to take in two arrays, a secret "key" and a word, composed of 5 and 7 characters respectively, and then by comparing the user-inputted key with a static, hidden key, spit out a NEW translated word which consists of different characters imposed by the user-inputted "key."
Anyways, the function is more-or-less not important because I can't even get my program off the ground! I am new to the fgets() function and am more or less poking around in the dark. Could anyone point me in the right direction?
Thanks.
The reason why fgets is only reading partial input is because the buffer too small. You need to increase the buffer size. Below is working code And what is the content of input[]
array?
void main()
{
int i,j,k,n;
char key[64], input[64], word[64], output[64];
printf("Enter key:");
fgets(input, sizeof(key), stdin);
input[strlen(input)-1] = '\0';
printf("Enter word:");
fgets(word, sizeof(word), stdin);
word[strlen(word)-1] = '\0';
//I am trying to store two
for (i = 0; i<7; i++) { //user-inputted arrays and then
for (j = 0; j<5; j++) { //do stuff with them. Fails before
if (word[i] == key[j]) { //I even get to the for loop.
output[i] = input[j];
}
}
}
printf("%s\n",output);
}
#include <stdio.h>
int main (void)
{
int n;
printf("Give the number of words you want to input.");
scanf("%d",&n);
int letters[n],i,j,count,key,k;
char str[100];
//Scans each word, counts it's letters and stores it in the next available
//position in "letters" array.
for (i=0;i<n;i++)
{
j=0;
printf("Give the next word.");
do{
str[j] = getchar();
j++;
}while (str[j-1]!='\n');
str[j-1] = '\0';
letters[i] = j;
}
//Compacts the data by figuring out which cells have the same number of letters
for (i=0;i<n;i++)
{
key = letters[i];
count = 0;
for (j=i+1;j<=n;j++)
{
if (key==letters[j])
{
count += 1;
letters[j] = 0;
}
}
letters[i] = count;
}
//creates a histogram
i=0;
do{
printf("%d|",i);
for (j=1;j<=letters[i];j++)
{
printf("*");
}
printf("\n");
i++;
}while ((i<=n));
return 0;
}
I understand that getchar(); reads, the first enter (\n) , user hits, to give the amount of words he wants to input, and thus expects one less word.
Also, I get an infite loop for some reason at the end. Any help and ideas would be appreciated. Thanks in advance.
Change the first block of your code to look like this:
(test the output of getchar, and continues only if not EOF)
for (i=0;i<n;i++)
{
j=0;
printf("Give the next word.");
do{
a = getchar();
if(a >= 0)
{
str[j] = a;
j++;
}
else break;
}while (str[j-1]!='\n');
str[j-1] = '\0';
letters[i] = j;
}
But regarding your question: How can I replace getchar();? Have you considered using scanf()?
EDIT
Here is a simple example of using scanf() and printf() to prompt for input and then display input. It will allow user to input entire words or sentences (up to 80 characters) until 'q' is entered. Not exactly what you are doing, but you should be able to adapt it to your code... (run this)
int main(void)
{
char buf[80]={""};
while( strcmp(buf, "q") != 0) //enter a 'q' to quit
{
buf[0]=0;
printf("enter string:\n");
scanf("%s", buf);
printf("%s\n", buf);
}
}
Wouldn't it be easier to update the letter count in the first loop?
memset(letters, 0, n);
for (i=0;i<n;i++)
{
char* s = str;
int j=0;
printf("Give the next word.");
do{
*s = getchar();
++j;
}while (*(s++)!='\n');
s[-1] = '\0';
letters[j-1]++;
}
As a result the second loop will be unnecessary.
The following two lines have the wrong end condition; should be <n, not <=n. Currently they retrieve an uninitialized array element. Since you declared str as a local variable, that element is typically populated with garbage, i.e. a very big random number. That might explain why it takes extreme long (but possibly not forever) for the last loop to finish.
for (j=i+1;j<=n;j++)
}while ((i<=n));
Also, I assume line n of the histogram should contain the number of words that have n letters? That's not what you're doing right now.
letters[i] = count;
That line should have been:
letters[key] = count;
But to make that work, you should not overwrite the same array letters; you must declare a new array for your histogram, otherwise the second loop will destroy its own input.
By the way, str seems totally redundant. Is it there for debugging purposes?
I need to write a program that will read in a sentence and output the number of words in the sentence. I have the program done, but the problem is that my program is counting the spaces inbetween the words as characters. How do I omit those spaces and just display the number of words in the string? I was thinking I need some type of loop, but I don't know how to execute it.
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define pause system("pause")
main() {
char mystring[155];
int counter = 0;
printf("Enter your name: ");
scanf("%[^\t\n]", &mystring);
printf("Your name is %s\n", mystring);
// find out the number of characters in the string
counter = strlen(mystring);
printf("There are %i words in the sentence. \n", counter);
// find out how many WORDS are in the sentence. Omit spaces
pause;
} // end of main
Again, as someone has already said, use strtok. If you need to know more about it,
http://www.cplusplus.com/reference/cstring/strtok/
If you want to do it without using any existing API's (I don't know why you would want to do that unless it's a class project), then create a simple algorithm with a pointer to traverse the string and skip spaces while incrementing count.
As people have said before, this will be a good exercise for you, so don't ask for code. And there's always google..
Your function would look something like this :
_getNumberOfWords(char[] string) {
int count = 0;
for (int i=0; string[i] != '\0'; i++) {
if (string[i] == " ") {
for (int j=i; string[j] != '\0'; j++) {
// This is to handle multiple spaces
if (string[j] != " ") break;
}
count++;
}
return count;
}
You could also try to do a :
char * strtok ( char * string, const char * " " );