So I’ve just started learning C for a class of mine, and I have been working on this assignment, but this part has me perplexed. I have some code that essentially looks like:
#include <stdio.h>
#include <string.h>
int main(void)
{
int one = 0;
int two = 0;
char oneWord[100];
char twoWord[100];
printf("Enter a two digit number: ");
scanf("%d%d", &one, &two);
strcpy(firstWord, "Test");
strcpy(secondWord, "Two");
printf("%s", firstWord);
return 0;
}
Now, logic/purpose of the program aside, what I cannot figure out is why that scanf statement is resulting in an infinite loop? I determined that was that cause of the problem when I commented it out and the final printf statement worked just fine.
I tried changing it to scanf("%d,%d", %one, %two) and that seemed to work fine when I added a comma to the input. But I want to just be able to take a number like 55 and break it into 2 digits. What exactly am I doing wrong here?
What you run into is not an infinite loop, but rather
scanfwaiting for more input.The
d-format-specifier means a decimal number, so anything like “0”, “41”, or “2342345”.After you have entered the first number, you expect the program to continue, but
scanfhas just completed the first%d, soscanfis waiting for you to fulfill the second%d. This is what seems to you an infinite loop, but really isscanfdoing what you ordered it to.scanfcannot guess how many digits for each number you desire. But you can tell it how you want it, with a width-specifier that tells how many characters each information is composed of:with error handling: