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.
Related
This question already has answers here:
scanf causing infinite loop in C
(2 answers)
Closed 2 years ago.
im just starting C and i dont know why this is happening. When i excuted the program it only stored 1 value in the service_code array. For some reason, the scanf() is keeping the loop counter ias 0. I couldn't find a solution. The scanf() is causing the forloop to to run infinitely. Does anyone know how to fix this?
#include <stdio.h>
#include <string.h>
int main() {
char name [100];
char str [10];
int discount = 0 ;
int age;
char service_codes[4][6];
printf("Welcome to Nelson Lanka Hospital \n");
printf("Our Services : \n SV105 - Doctor Channeling \n SV156 - Pharmacy \n SV128 - Laboratory \n SV100 - OPD \n \n");
printf("Enter your Details \n Name : ");
scanf("%[^\n]",name);
printf(" Enter age : ");
scanf("%d",&age);
printf(" Enter the Sevice code for the service you need : ");
scanf("%s", str);
strcpy(service_codes[0], str);
for(int i = 1; i<4; i++){
char yn [2] = "y";
printf("Do you need any other sevices? (y/n) : ");
gets(yn);
if (strcmp(yn, "n")==0){
break;
}
printf(" Enter the Sevice code for the service you need : ");
scanf("%s", str);
strcpy(service_codes[i], str);
printf("%s \t %s \t %d \n",service_codes[i],str,i);
}
for (int x = 0; x<4; x++){
printf("%s \n",service_codes[x]);
}
}
For some reason, the scanf() is keeping the loop counter i as 0.
You're probably having a buffer overflow that is altering the variables in the stack (such as the variable i). I see at least two points in your program where a buffer overflow may occur:
scanf("%s", str);: the array str only has room for 9 characters (plus 1 end null character used as a string terminator). If you type in a string longer than 9 characters (including the newline and carriage return characters that are appended when you hit ENTER) then scanf will corrupt the stack.
strcpy(service_codes[i], str);: each element in the array service_codes is defined to have 6 bytes each (room for 5 characters plus 1 end null terminator). By copying a string like this, in which str may be longer than service_code, you'll run into a buffer overflow.
C is a powerful language that allows you to do anything, even shooting at your own feet. You must be careful at every line you write in your code!
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 4 years ago.
Improve this question
I' ve inserted the followings input for the follow program:
a b c d e
After the e letter I've pressed Enter, but the program blocks on scanf for i equal to 3.
Seems that scanf is not able to fetch other character from stdin.
Thanks in advance for your help.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[5];
for (int i = 0; i < 5; i++)
{
scanf("%c ", a + i);
printf("i = %d a[%d] = %c \n", i, i, a[i]);
}
int i = 0;
while( i < 5 )
{
printf("%c ", a[i]);
i++;
}
return 0;
}
It doesn't block when i == 3 -- it completes that iteration -- it blocks when i == 4.
That's because of the space after the %c in the scanf format -- a space causes scanf to read input and skip whitespace up until it finds a non-whitespace character. That non-whitespace character will then be left in the FILE input buffer as the next character to be read. So in the 5th iteration of the loop (i == 4), it reads the e then reads whitespace looking for non-whitespace. So the newline is skipped over (it's whitespace) and it starts (trying to) read the next line which blocks.
Once you provide the next line (assuming its not empty/all whitespace), it will get a non-whitespace character and scanf will return.
Using scanf to fetch a single character at a time from stdin is not a good idea. If the user types more than one character, you can overflow the buffer as there is no room for the null character. This also leaves excess characters in stdin.
Another idea is to use a special format string flag to fetch 5 characters at once, and then print them or do whatever you want with them.
You can use the flag "%5c", where 5 is any integer number, that reads, scan exactly 5 characters.
Here is the modified version of your code
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[5];
scanf("%5c", a);
int i = 0;
while( i < 5 )
{
printf("%c ", a[i]);
i++;
}
return 0;
}
Now there is no blocking.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to read n integers from user during execution and the numbers are separated by spaces. It would be the best to be received as an array. For input 1 22 3 445 3, the result is, array[0]=1, array[1]=22 and so on. I have to do it in C. Can't use
scanf("%d %d %d", &var1, &var2, &var3);
because, I don't know how many such numbers would be inserted. The value of n would be read from user just before reading this data.
enum { MAX_NUMBERS = 1000000 }; // Choose appropriate upper bound
int n;
if (scanf("%d", &n) == 1 && n > 0 && n < MAX_NUMBERS)
{
int array[n];
for (int i = 0; i < n; i++)
{
if (scanf("%d", &array[i]) != 1)
…process error — terminate loop?…
}
…use array…
}
You can read multiple numbers with scanf() using a loop as shown. You've no idea whether they were all presented on a single line, or each was on its own line, or whether there were many blank lines between successive numbers (or any permutation of all these possibilities).
The scanf() family of functions basically do not care about newlines — it is hard to force them to do so. When you care about line-based input, use fgets() or POSIX function getline() to read a line and sscanf() — or other string parsing functions — to process the line.
I'm assuming support for C99 with VLA (variable length arrays). The principles are the same without that support — the mechanics are a little different (and there are multiple options for how to do it).
Use fgets() and then strtok() with atoi().
Take the numbers as a string.
Here is one way to do it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char numbers[100];
int myn[100];
printf("Give me numbers..\n");
fgets(numbers,100,stdin);
const char s[2] = " ";
char *token;
token = strtok(numbers, s);
int i=0;
myn[i]=atoi(token);
while( token != NULL )
{
i++;
printf( " %s\n", token );
token = strtok(NULL, s);
myn[i]=atoi(token);
}
printf("You gave me: ");
for (int j=0; j<i; j++){
printf ("%d, ", myn[j]);
}
return(0);
}
The above C program does exactly what you want. At the for loop, it prints to the screen the numbers you gave from keyboard. The "problem" would be much easier by using enter instead of spaces between the numbers.
Click on the links, to see very useful details about the functions used.
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
Part of my assignment is to get user input; then, if the input is incorrect, prompt them to try again. When I use if statements and while loops in this way, they completely skip over the scanf command, and the program either runs infinitely or terminates immediately, skipping over the second chance for user input. Any idea how to fix this?
#include <stdio.h>
int main(void)
{
int number;
printf("please insert positive number\n");
scanf(" %d", &number);
// if the user inputs a value that is not a positive integer, it becomes false
// i want the if statement to re-prompt them to input the correct value
if (number <= 0)
{
printf("try again\n");
scanf(" %d", &number);
}
return 0;
}
scanf Returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned.
The scanf function reads data from the standard input stream stdin and writes the data into the location given by argument. Each argument must be a pointer to a variable of a type that corresponds to a type specifier in format.
I recommend handle errors . it will happen in Real World code. (write Concise and robust Code).
so i recommend something like this:
#include <stdio.h>
int read_positive_int(int *n){
int retry = 3;
do{
printf("Please enter a positive number:\n");
if (scanf("%d", n) == 1){
if (*n > 0) return 1; //ok
}
} while (--retry);
return 0; //error
}
int main(void)
{
int n;
if (read_positive_int(&n))
printf("n = %d\n", n);
else
printf("error\n");
}
i hope this helps.
the code does what it's written to do, so in your case it's following:
message to user: enter a positive number
scanf: reads user's input
determine, if the number is positive
if yes - the if body will not be executed
and program ends
if not - print a message, read a number and program ends
the thing you are looking for is a loop
you want to do something like this:
while the entered number is not positive, ask the user to enter the number again
that's what loops are used for
int number;
printf("please insert positive number\n");
scanf("%d", &number);
while (number <= 0) {
printf("try again\n");
scanf("%d", &number);
}
return 0;
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]);
}
}