I want to print three char variables with a for loop but I don't know why only last is printed.
This is my code:
int main (){
int i, j, k;
char word[50], old[1], new[1];
printf("Enter a word: ");
gets(word);
printf("Enter desired letter to substitute: ");
gets(old);
printf("Enter the new letter: ");
gets (new);
for (i = 0; i<strlen(word); i++){
printf("%c", word[i]);
}
for (j = 0; j<strlen(old); j++){
printf("%c", old[j]);
}
for (k = 0; k<strlen(new); k++){
printf("%c", new[k]);
}
}
I don't get why this simply code doesn't work.
Your code overflows the buffers for old and new because they do not contain enough space for a 1 character string. In C strings needs to be null terminated, so a char array must always be one element longer than the maximum number of characters it must contain. For example your word array can only hold a 49 character string, since the 50th element must be the null.
So old and new must both be char[2] arrays.
Your loops are unnecessary and incorrect. You can print the values directly without specifying the index. In your post you're trying to loop through each index and print a character at a time. Here's what you should do:
int main (){
int i, j, k;
char word[50], old[2], new[2];
printf("Enter a word: ");
gets(word);
printf("Enter desired letter to substitute: ");
gets(old);
printf("Enter the new letter: ");
gets (new);
printf("%s\n", word);
printf("%s\n", old);
printf("%s\n", new);
}
Related
#include<stdio.h>
int main(){
char name[3];
float price[3];
int i,page[3];
printf("enter the name price and book\n");
for(i=0;i<3;i++){
scanf("%s",name[i]);
printf("enter character:\n");
}
for(i=0;i<3;i++) {
scanf("%f",&price[i]);
printf("enter floating point number:\n");
}
for(i=0;i<3;i++) {
scanf("%d",&page[i]);
printf("enter digit:\n");
}
printf("\n");
for(i=0;i<3;i++) {
printf("%s\n",name[i]);
}
for(i=0;i<3;i++) {
printf("%f\n",&price[3]);
}
for(i=0;i<3;i++){
printf("%d\n",&page[i]);
}
return 0;
}
When I was trying this code, I thought this was quite simple to do but I realized, there is something which I am missing in the code. The main problem with this code is it is not scanning the values of price and pages. I don't understand where I am mistaken.
So, please correct my code so that it will print the values of name price and pages.
There are a number of issues in your code. First and foremost, the %s specifier (for both the scanf and printf functions) expects a string argument (that is, a nul-terminated array of char for printf or an array sufficiently large to hold the input characters plus that terminator, for scanf); however, you are attempting to read (and print) a single char value in each of the relevant for loops.
To fix this, use the %c format specifier, instead of %s. However, when you use this, the newline character that is generated when you press the Enter key will be left in the input buffer, and that will be read as the actual char input on the next iteration of the first for loop. To clear any such newline (or, indeed other whitespace) from the input before the real input, add a space in the format string before the %c. Also, when using this, you will need to pass the address of each name element: scanf(" %c", &name[i]);.
Further, the printf function takes the actual values of the variables to be output, rather than their addresses – so remove the & from the arguments in your printf calls. (Also, and I assume it's a typo, the price[3] expression should be price[i] – the former attempts to access an out-of-bounds element of the price array.)
Another issue is that, in each of your input loops, you call the scanf function before you display the relevant prompt. In the code below, I have reversed your printf and scanf lines in each of those input loops.
Here's a possible fixed version:
#include<stdio.h>
int main()
{
char name[3];
float price[3];
int i, page[3];
printf("enter the name price and book\n");
for (i = 0; i < 3; i++) {
printf("enter character:\n");
scanf(" %c", &name[i]);
}
for (i = 0; i < 3; i++) {
printf("enter floating point number:\n");
scanf("%f", &price[i]);
}
for (i = 0; i < 3; i++) {
printf("enter digit:\n");
scanf("%d", &page[i]);
}
printf("\n");
for (i = 0; i < 3; i++) {
printf("%c\n", name[i]);
}
for (i = 0; i < 3; i++) {
printf("%f\n", price[i]);
}
for (i = 0; i < 3; i++) {
printf("%d\n", page[i]);
}
return 0;
}
I'm just trying to write a simple code where I enter a 3 letter word and then print out the word I entered. I tried doing this by creating the array, and then making a loop where the counter "i" keeps incrementing and the scan function keeps working for each index value of the letter I add.
But there seems to be some error in line 16, and even then not sure if the logic of the code is right.
#include <string.h>
#define ALEN 3
int main (void)
{
char array[ALEN];
int i;
printf("Enter a 3 letter word> ");
scanf("%s", array);
for(i=0; i<ALEN; i++)
{
array[i] = array[ALEN];
scanf("%s", &array[i]);
}
printf("\n");
printf("Word entered: %s", char array[i]);
return 0;
}```
I'm trying to ask K amounts of words to add them in a matrix.
And i have 2 problems:
I tried to make the condition that the strlen(string) must be less than the size of n(matrix size). But when it enters the do while loop, it never quits.
How can i make the for loop to repeat until k words are entered?
I already tried a few days ago, and the do while worked fine. Until i changed something and it got messy.
/* Enter the matrix dimension */
int n;
do{
printf("\nEnter the matrix size");
scanf("%d", &n);
}while(2>n);
/* Ask for the amount of words the user will enter */
int k;
do{
printf("\nInsert how many words you will enter:");
scanf("%d", &k);
}while(k<0);
/* k Words loop */
int amountOfWords=0;
char string[20];
int i;
for(i=0; i<k; i++, amountOfWords++)
{
do {
printf("\nEnter the %d word:\n", amountOfWords+1);
scanf("%s", &string);
}while(strlen(string) > n);
}
The problem with your current code is that the amountOfWords variable is never incremented inside the do-while loop, so the condition for the loop strlen(string) > n is always true.
Here is one way to fix the problem:
int amountOfWords=0;
char string[20];
for(int i=0; i<k; i++)
{
do {
printf("\nEnter the %d word:\n", i+1);
scanf("%s", string);
}while(strlen(string) > n);
amountOfWords++;
}
In this way, if the user enters a word that is longer than the maximum size (n), the loop will ask again for a word until a valid word is entered, and the variable amountOfWords will be incremented after a valid word is entered.
Another way to do it could be using a while loop, like this:
int amountOfWords=0;
char string[20];
int i=0;
while(amountOfWords<k)
{
printf("\nEnter the %d word:\n", amountOfWords+1);
scanf("%s", string);
if(strlen(string) <= n)
{
amountOfWords++;
}
}
In this way, the loop will keep running until amountOfWords reaches the desired amount of words (k).
I am attaching the code for the same.Its working fine.But once i enter a number less than the previous one it stops giving desired output.Any help/suggestion shall be greatly appreciated.
int i=1;
int j=0;
int n;
char ch;
while(ch!='n')
{
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);
while(i<=n)
{
j=j+i;
i++;
}
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%s",&ch);
}
return 0;
In your outer while loop, you're never resetting the value of the variable i back to 1, or j back to 0. That is why subsequent loops will produce an incorrect sum.
There are a smattering of bugs in this code, including:
Comparison to uninitialized value of of ch in the initial while expression.
Failing to reset i and j for each outer-loop iteration
Failing to test for data-read success in either scanf call to ensure proper input.
The continuation scanf("%s", &ch) is simply wrong for a single character with skipped whitespace (which you must do to avoid reading the newline after your list integer input). Unless EOF or an error state is reached, what you have now is guaranteed to invoke undefined behavior, as a string-read of at least one character requires at least two for storage (the character, and a subsequent terminator).
Addressing all of those:
#include <stdio.h>
int main()
{
char ch;
do
{
int n;
printf("Enter the number upto which you want the sum of \n \n");
if (scanf("%d", &n) != 1) // See (3)
break;
int j = 0; // See (2)
for (int i = 1; i <= n; ++i) // See (2)
j += i;
printf("%d \n", j);
printf("Do it with another number? Y/N \n \n");
if (scanf(" %c", &ch) != 1) // See (3) and (4)
break;
} while (ch != 'n' && ch != 'N'); // See (1)
return 0;
}
Everything here is self-explanatory when referred to the previous bug punch list, save for maybe the format string for reading the single character. You mentioned in comments that you tried %c but it skipped to another loop iteration. That's because you didn't have the leading whitespace " %c" that tells scanf to skip white space before extracting the next argument. With that, it should work as desired.
You need to reset i and j for every n.
i = 1;j=0;
while(i<=n)
{
Also your format specifer is wrong. For char, it should be %c and not %s
scanf("%c",&ch);
The simplest solution is to set i to 0 at the outer while:
int i=1;
int j=0;
int n;
char ch;
while(ch!='n')
{
i = 0;
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);
while(i<n)
{
j=j+i;
i++;
}
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%s",&ch);
}
return 0;
Note that I have changed <= to < for your inner while, since you do not want to increment the value if the same n is inputted one after the other.
#include<stdio.h>
int main(){
int n;
char ch;
while(ch!='n')
{
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);
int i=1;//it should be 1 in every loop of the number
int j=0;//the sum should also be initialized to zero to erase the previous value
while(i<=n)
{
j=j+i;
i++;
}
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%c",&ch);//this is a char not a string
}
return 0;
}
Due to the i is not initializing to 1 when the loop is coming for the second time there it is not going inside the loop and printing the previous value .
This question already has answers here:
what is the purpose of putting a space in scanf like this scanf(" %c",&ch) in place of scanf("%c",&ch)? [duplicate]
(6 answers)
Closed 6 years ago.
I have just written a program to reverse a word. I have first compiled the program as follows:
//This program will reverse a given word
#include <stdio.h>
int main()
{
int letters, i, j;
printf("Enter the number of letters in your word: ");
scanf("%d", &letters);
int word[letters];
printf("Enter %d Letters: ", letters);
for( i = 0; i < letters; i++){
scanf("%c", &word[i]);
}
for( j = i - 1; j >= 0; j-- ){
printf("%c", word[j]);
}
return 0;
}
Then, I inputted 5 to store in letters and the word "rubel" (ignore the inverted comma) to reverse. The expected output was "lebur". But unfortunately i got ebur. then i recompiled the code as below:
//This program will reverse a given word
#include <stdio.h>
int main()
{
int letters, i, j;
printf("Enter the number of letters in your word: ");
scanf("%d", &letters);
int word[letters];
printf("Enter %d Letters: ", letters);
for( i = 0; i < letters; i++){
scanf(" %c", &word[i]);
}
for( j = i - 1; j >= 0; j-- ){
printf("%c", word[j]);
}
return 0;
}
This time i got expected output which is "lebur". Now, my question is what was wrong before that i didn't get expected output and what have i just done by putting a space that this time i got the expected result. Thanks in advance.
In the first case word[0] became \n (you entered 5\n). In the second case the \n was skipped because you told scanf to skip whitespace characters (by ).