Loop is running more than specified in C? Why? [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 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]);
}
}

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);

scanf() running only once inside for loop [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 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;

Number in for loop doesn't increment [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 4 years ago.
Improve this question
I got the task to scan 10 numbers that will later on be converted into characters. The problem is that I don't get why there is an infinite loop if I don't enter 0. I got the task right with array but I am interested why does this happen in example bellow.
#include <stdio.h>
#include <stdlib.h>
int main() {
/**
* for the example enter numbers: 8 5 12 12 15 23 15 18 12 4 -> helloworld
*/
char n;
// message needs to be 10 numbers long.
for (int i = 1; i <= 10; i++){
// enter message in numbers.
scanf("%d", &n);
// check if it is 0. if it is, end the message.
if(n == 0) {
printf("\nEnd of the message!");
break;
// if number is not 0, add 64 to transform to char.
}else {
n = n + 64;
// print the char.
printf("%c ", n);
// print the i, that doesn't increment.
printf(" -> i:%d\n", i);
}
}
return 0;
}
You are using
char n;
...
scanf("%d", &n);
You cannot use %d with char. You should change n to an int or use %c for scanf and printf.
int n;
...
scanf("%d", &n);
OR
char n;
...
scanf("%c", &n);
You are using a char to read an int. The scanf fails and input remains in the buffer and so scanf keeps on reading the same value again and again resulting in an infinite loop.
So, declare n as an int.
It is a good practice to check the return value of scanf so that you will know if the input has been read properly.
The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure
The problem is with the scan!
scanf("%c", &n);
%d for ints, %c for chars, %s for strings, %f for floats!
scanf("%d", &n) reads an int into n. Since n is a char this results in the 3 bytes that appear after n being overwritten by the scanf. In your case the variable i was allocated within memory that overlaps those 3 bytes and so each call to scanf modifies the variable i resulting in a potentially infinite loop. Use %c to read in a character rather than %d.

take string input at 2-d array in c [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
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.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
i am new in c,so i want to input string at 2-d array,but don't print string.what's wrong in this code and how can i fixed this problem.thanks in advanced
#include <stdio.h>
#include<string.h>
int main()
{
char col[100][100];
int i,j;
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
scanf("%s",
&col[i][j]);
}
}
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
printf("%s\t",col[i][j]);
}
printf("\n");
}
return 0;
}
You're printing a char with %s. Change instead to %c.
printf("%c\t", col[i][j]);
With %s printf will print all characters until a \0 is found and in your case there's none which will lead to unexpected behavior.
In a 2D character-array, each element col[i][j] is a character. But , you're taking string and printing string using the printf and scanf statements. You need to change the following:
scanf("%c",&col[i][j]);
and
printf("%c\t",col[i][j]);
Use %c instead of %s because %s is a identifier of String. What I found in your code is that you said you want string as input but you are taking char by char as a input. I will suggest you to use pointer to take String as a input in 2D char Array.
Taking String as a input in 2D char Array
#include <stdio.h>
#include <string.h>
int main() {
char *s[100];
char s1[100];
int i;
for(i=0;i<5;i++){
scanf("%s", s1);
s[i]=strdup(s1);
}
for(i=0;i<5;i++){
printf("%s\n", s[i]);
}
return 0;
}
What I am doing is that I am taking the input from user in s1 and put that in the 2D char array. By using this method you have put each string in a each row.
Hopefully that help.

Missing last character [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am reversing a String without using inbuilt function . its reversing every character but missing last character
here is the program
#include<stdio.h>
void main()
{
char str[10],rev[10];
int i,j,k;
clrscr();
printf("enter the string \n");
scanf("%s",str);
for(i=0;str[i]!='\0';i++)
k=i-1;
for(j=0;j<=i-1;j++)
{
rev[j]=str[k];
k--;
}
rev[j]='\0';
printf("reverse=%s",rev);
getch();
}
I am not getting why the last Char is missing
k = i;
You miscounted it.
Your expression k = i-1; doesn't leave space for the whole reversed string.
The code that computes the length of the string is missing a semicolon:
The compiler interprets it as
for(i=0;str[i]!='\0';i++)
k=i-1;
while the intention has probably been to have
for(i=0;str[i]!='\0';i++)
;
k = i - 1;
Demo on ideone.
Now that the code is "working", you should fix an error that could cause undefined behavior: limit the length of the input to 9 characters in scanf, like this:
scanf("%9s", str);
Without 9, the user could cause undefined behavior by entering more than nine characters, and overflow your ten-byte buffer.

Resources