scanf() running only once inside for loop [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am a newbie to C programming. I am trying to solve a question using scanf in loop, but the problem is that scanf is only running once inside the loop. My code is:
#include <stdio.h>
#include <string.h>
int main()
{
int n;
int x=0;
scanf("%d", &n);
for (int i=1; i<=n; i++)
{
char stat[3];
scanf ("%s", stat);
if (strcmp(stat, "X++")==0)
x++;
else if (strcmp(stat,"++X")==0)
x++;
else if (strcmp (stat, "--X")==0)
x--;
else if (strcmp(stat, "X--")==0)
x--;
}
printf ("%d", x);
return 0;
}
Why is the scanf running only once even when n is 2, 3 or anything else?

This may be because the value of the variable n is destroyed by out-of-bounds write.
Your buffer stat don't have insufficient size to store 3-character string because there are no room to store terminating null character.
Increase buffer size and limit number of characters to read for safety.
Checking if reading is successful will make it safer.
char stat[3];
scanf ("%s", stat);
should be
char stat[4];
if (scanf ("%3s", stat) != 1) return 1;

Related

I face a problem in C. Input is wrong-- its say Segmentation fault [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
#include <stdio.h>
#include <string.h>
struct student_details{
char name[34];
int roll;
char section;
};
int main(){
struct student_details student[5];
for (int i = 0; i < 5; i++)
{
printf("Your full name = ");
scanf("%s", student[i].name);
printf("Your roll = ");
scanf("%d", student[i].roll);
}
return 0;
}
I think something is wrong with my code anyone please fix this.
When I run this code, it's Shows an error. after running this code this code take 1 time input and second input is skipped.
The scanf function expects to accept a format string and then pointers to the data you want to scan into. student[i].name is an array, which in this case decays into a pointer to its first element. This works.
Note: This array only contains 34 characters. With the null terminator, you want to use a width specifier with scanf to limit the input and prevent a buffer overflow. "%33s"
When you try to read the roll:
scanf("%d", student[i].roll);
student[i].roll is an int, not a pointer. But pointers are numbers, so this will compile. Your compiler should warn you about it, though. But, then the program tries to dereference this value it thinks is a pointer, and a segmentation fault occurs.
What you want to do is pass the address of student[i].roll.
scanf("%d", &student[i].roll);

How can I fix Address boundary error in C? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm new to C,and want to write a simple program that takes a user input and prints it out a specific amount of times back to them.
#include <stdio.h>
#include <stdlib.h>
int main() {
char* str[100];
int *p = malloc(sizeof(int) * 10);
int amount;
*p = amount;
int i;
printf("\nType anything!\n");
scanf("%s", str);
printf("\nHow many times?\n");
scanf("%d", amount);
for (i=0; i<=amount; i++) {
printf("%s", str);
}
return 0;
}
It works fine,until after pressing entering the amount of times,when the program crashes with the Fish shell saying "fish: “./a.out” terminated by signal SIGSEGV (Address boundary error)".
Address boundary error tells me that maybe I haven't allocated memory for something,but how would I go about doing that? I've tried using malloc with a pointer pointed at amount but it doesnt seemed to have solved anything.
It's remarkable how many issues there are in such a short chunk of code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[100];
int amount;
printf("\nType any word!\n");
if (scanf("%99s", str) != 1)
{
fprintf(stderr, "Failed to read a string\n");
return(EXIT_FAILURE);
}
printf("\nHow many times?\n");
if (scanf("%d", &amount) != 1)
{
fprintf(stderr, "Failed to read an integer\n");
return(EXIT_FAILURE);
}
for (int i = 0; i < amount; i++)
{
printf("%s\n", str);
}
return 0;
}
The signature of main() is a full prototype.
The type of str is corrected (or, at least, changed and made usable).
The code related to p and malloc() is not needed.
The variable i is moved into the for loop (assumes a C99 or later compiler; if not available, what you had was OK).
Change "anything" to "any word" because %s skips white space and then reads non-spaces up to the next white space.
Limit the amount of input to prevent overflows.
Report if there's a problem reading the string and exit.
Fix the scanf() to pass &amount (key change).
Check for success reading amount and report failure and exit.
Define i in the loop control (C99).
If the user requests one copy, only print one copy (change <= to < — that's an idiomatic C loop now).
Output newline after each word. There are other ways to present the data, including the one chosen originally, but you should at least end the output with a newline.

No Error but why we don't get input for second scanf() statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
#include<stdio.h>
int main()
{
char ch;
int i;
scanf("%c", &i);/* i know this must be reversed for next input but I want to know the impact of this code if we use scanf type char for integer data type*/
scanf("%d", &ch);
printf("%c %d", ch, i);
return 0;
}
No Error but why don't get input for second scanf() statement
You declared i to be an int and ch to be a char
In your scanf you have %c for i and %d for ch while %c is for chars and %d for ints.
So just turn them around and you'll be fine.
With printf you have the correct format.

strcmp does not return 0 on equal strings in c [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
So im making a program that checks if a word is a palindrome but when it comes to comparing the final strings at the end even if they are the same i get a -1 result edit: copy pasted the exact same code i used
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main()
{
char input[50];
char test[50];
int ret;
printf("Enter word or phrase to compare ");
fgets(input,sizeof(input),stdin);
strcpy(test,input);
strrev(input);
ret = strcmp(test,input);
if(ret == 0)
printf("\n this is a palindrome ");
else
printf("\n this is not a palindrome");
}
For input i used "ala" which i know is a palindrome i get the result
this is not a palindrome
Demonstration on IDEONE.
The problem is that you call strrev without stripping off the newline from your input obtained from fgets. This causes your reversed string to have the newline at the beginning of the string, which would cause a mismatch even if you intended to provide a palindrome as the input.
While there are various ways to achieve this, one way would be to look at the last byte of your input, and see if it is a newline character. If it is, remove it.
if (fgets(input,sizeof(input),stdin) == NULL) {
/* todo: ... handle error ... */
return 0;
}
len = strlen(input);
if (input[len-1] == '\n') input[--len] = '\0';
strcpy(test,input);

Loop is running more than specified in C? Why? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
If I enter the number 5, this loop has to run 5 times but it is running 6 times. What is the problem?
int main(){
int i, *arr, size;
printf("Please enter the Number: ");
scanf("%d ",&size);
arr = (int*) malloc(size * sizeof(int));
for(i = 0; i < size; i++){
scanf("%d ", &arr[i]);
}
}
Remove the trailing space from the scanf() format string being used in the loop.
It causes scanf() to discard all whitespace after having read an int (%d), until it finds something that is not whitespace. On the fifth iteration of the loop, scanf() reads the int, and keeps going until it finds non-whitespace. This gives the illusion of needing to read one more integer.
On the last call of scanf(), any non-whitespace character after the integer data will cause reading to end.
Remove the space here:
This:
scanf("%d ",&arr[i]);
^
should be:
scanf("%d",&arr[i]);
I too faced the similar problem. To get it perfect please remove the
space after %d in the loop. It should work. Might be some property of scanf.
int main(){
int i, *arr, size;
printf("Please enter the Number: ");
scanf("%d",&size);// Note the change here
arr= (int*) malloc(size * sizeof(int));
for(i= 0;i < size;i++){
scanf("%d",&arr[i]);
}
}

Resources