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);
}
Related
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
Here is the situation:
First, The input consists of the number of test cases, m, in the first line and followed by m test cases. Each test case consists of a string with less than 256 characters. The String may contain "Space bar". My Programming language is C.
Then, here is my problem. I cannot find any problem in my code and I can perfectly run the example with correct result. However, when I upload it onto online judgement system, it shows "WA(Wrong Answer)".
Here is my code.
#include<stdio.h>
int numberOfDigit(char input[255])
{
int num = 0;
for (int i = 0; input[i] != '\0'; i++) {
if (input[i] >= 48 && input[i] <= 57)
num++;
}
return num;
}
int main()
{
int numberOfTestCase;
char input[255];
int digit[9999];
scanf("%d", &numberOfTestCase);
for (int j = 0; j < numberOfTestCase; j++) {
fseek(stdin, 0, SEEK_END);
gets(input);
digit[j] = numberOfDigit(input);
}
for (int k = 0; k < numberOfTestCase; k++) {
printf("%d\n", digit[k]);
}
return 0;
}
I want to explain something in my process of coding.
Because the input contains space character, I use gets() function so that I can get a string without stopping by typing space.
However, if I don't add fseek(stdin, 0, SEEK_END);, gets() only appears numberOfTestCase-1 times, I asked on stackOverflow, and was advised that fseek(stdin, 0, SEEK_END); can solve the problem, which I don't know why. But when I add it, the problem is solved, but it fails tests in the online judgement system.
What is my mistake?
fgets() would stop reading input if it sees a newline. Also fseek() may not work on stdin and it's unnecessary for your purpose. Instead you can fgets() to read the first line too instead of scanf(). And then you can use sscanf() to read the input number.
Something like:
fgets(input, sizeof input, stdin);
sscanf(input, "%d", &numberOfTestCase);
for (int j = 0; j < numberOfTestCase; j++) {
fgets(input, sizeof input, stdin);
digit[j] = numberOfDigit(input);
}
for (int k = 0; k < numberOfTestCase; k++) {
printf("%d\n", digit[k]);
}
You can also use the chracter constants instead of hard-coding ASCII values, which is more readable and portable:
for (int i = 0; input[i] != '\0'; i++) {
if (input[i] >= '0' && input[i] <= '9')
num++;
}
Trying to write that function checks whether all the letters in word appear in s, in the same order. If a letter appears several times in word, then it should appear
at least as many times in s.
For example:
containsLetters2("abcdef", "aaabbb")
returns 0 because there are no three appearances of the letter "a" followed by three appearances of the letter “b”.
This:
containsLetters2("axaxxabxxbxbcdef","aaabbb")
returns 1
I can't understand whats wrong in my code:
int containsLetters2(char *s, char *word)
{
int j,i, flag;
long len_word, len_s;
len_s=strlen(s);
len_word=strlen(word);
for (i=0; i<=len_word; i++) {
flag=0;
for (j=0; j<=len_s; j++) {
if (*word==*s) {
flag=1;
word++;
break;
}
s++;
}
if (flag==0) {
break;
}
}
return flag;
}
int main() {
char string3[MAX_STRING] , string4[MAX_STRING];
printf("Enter 2 strings for containsLetters2\n");
scanf ("%s %s", string3, string4);
printf("Return value from containsLetters2 is: %d\n",containsLetters2(string3,string4));
return 0; }
for (i=0; i<=len_word; i++) {
flag=0;
for (j=0; j<=len_s; j++) {
if (*word==*s) {
You have two obvious problems. One is an off by one error. If the length is 10, then your code processes elements from 0 to 10, which is 11 elements, not 10. Second, you keep comparing *word to *s. What you want is word[i] compared to s[j].
There are lots more problems that are not as obvious. I'd strongly suggest you take a step back and start by documenting the algorithm your code is supposed to follow. That will make it easier to debug the code as you will know precisely what it is supposed to be doing.
The following code may not compile, but will do what you want it to do, hope it helps:
int containsLetters2(char *s, char *word) {
int lastIndex = 0;
for (int i = 0; i < strlen(word); i++) {
for (; lastIndex < strlen(s) && s[lastIndex] != word[i]; lastIndex++);
if (lastIndex == strlen(s)) {
return 0;
}
}
return 1;
}
You should preserve the value of variable j,
For example,
word = "aaabbb"
s = "axaxxabxxbxbcdef"
The 1st iteration, word[1] == s[1], then it break and come to the 2nd iteration,
at this time, j is reset to zero, and word[2] == s[1].
This got to be wrong.
Change your code as below to see if it helps,
i=j=0;
for (; i<len_word; i++) {
flag=0;
for (; j<len_s; j++) {
if (*word==*s) {
flag=1;
word++;
break;
}
s++;
}
if (flag==0) {
break;
}
}
#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?
the user enters a secret word and then from the alphabet choses a letter and if the letter is in the secret word it turns into an asterisk. i think the problem is in the two for loops because it does no seem to replace the letter with an asterisk.
int main ()
{
char secretword[20] = {};
char alphabet[27] = {"abcdefghijklmnopqrstuvwxyz"};
char guess;
int i = 0, k = 0;
int length = 0;
length = strlen(secretword);
printf("You Get six chances to guess all of the letters in a phrase\n");
printf("Enter the secret word/phrase: ");
scanf("%s", &secretword);
printf("Past guesses: ");
printf("%s\n", alphabet);
printf("Guess a character: ");
scanf("%s", &guess);
for(i = 0; i < 27; i++)
{
for(k = 0; k < length; k++)
{
if(secretword[k] == alphabet[i])
{
secretword[k] = '*';
}
}
}
printf("%s", secretword);
return 0;
}
First off, there is a big logic error. The two for loops:
for(i = 0; i < 27; i++)
{
for(k = 0; k < length; k++)
{
if(secretword[k] == alphabet[i])
{
secretword[k] = '*';
}
}
}
Says:
for all characters in the alphabet,
iterate over all characters in the string, and then
if that character in the string is equal to the current alphabet character:
replace it with an asterisk.
Because you're iterating over the whole alphabet, you'll replace all of the string with '*'s. What you probably want is something like:
for(k = 0; k < length; k++)
{
if(secretword[k] == guess)
{
secretword[k] = '*';
}
}
instead.
There are some other problems. This needs to be after secretword is read in:
length = strlen(secretword);
Otherwise you'll read the length of the uninitalised word. Change it to something like this:
printf("You Get six chances to guess all of the letters in a phrase\n");
printf("Enter the secret word/phrase: ");
scanf("%s", &secretword);
length = strlen(secretword);
Also, this:
scanf("%s", &guess);
Should probably be:
scanf("%c", &guess);
since you're planning to only read a char rather than a string.
Also, the 27 in this line:
char alphabet[27] = {"abcdefghijklmnopqrstuvwxyz"};
Is correct, because you want to include the null terminator at the end of the string.
However, this:
for(i = 0; i < 27; i++)
Will read up to alphabet[26], which will be a '\0'. You probably don't want to replace these '\0's in the string (and you won't see any if you're only going up to strlen(secretword) characters - since strlen() counts up to the first '\0'). Changing the loop to only go to 26 characters stops you doing an unnecessary pass over the secretword. It should probably be
for(i = 0; i < strlen(alphabet); i++)
Or, even better (as suggested by wildplasser):
char alphabet[] = {"abcdefghijklmnopqrstuvwxyz"};
....
for(i = 0; i < sizeof alphabet -1; i++)
One last thing - your program will crash if you don't have enough space in the secretword array to hold the string read in. You can get around this by asking scanf to read only 19 characters:
scanf("%19s", &secretword);
Note that scanf will terminate the string with a '\0', so %19s may put up to 20 bytes in to the string.
You set the length variable before secretword is initialized with an actual string so the length will always be zero (or garbage depending on how the compiler decides to initaliaze the variable secretword).
Try putting length = strlen(secretword); after scanf("%s", &secretword);. Without entering anything, strlen() will return 0, finishing the for-loop immediately.