Reputation: 51
I just started learning to program and I'm playing with pointers and scanf. I'm trying to make a program that asks the user for n (of cases in the code) and then the user is prompted to enter numbers n number of times, however once I'm in the terminal it doesn't stop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
int cases;
//prompt the user for number of cases
printf("cases:\n");
scanf("%d",&cases);
// will print the number of digits of the users number
for (int j = 0; j < cases; j++)
{
printf ("#%i:\n",j + 1);
char x;
int size;
scanf(" %s",&x);
size = strlen(&x);
//use printf to see what the program is doing
printf("the number of cases are:%d",cases);
printf("the current case is:%d\n",j + 1);
printf("the number of digits are:%i\n",si
}
//print back the users input
for (int i = 0; i < size; i++)
{
printf("%c", *(&x + i));
}
printf("\n");
}
After compiling and trying to press enter "#number" is not being updated and this is what appears:
cases:
3
#1:
564
the number of cases are:3
the current case is:13367
the number of digits are:3
or also
cases:
5
#1:
3
the number of cases are:5
the current case is:1
the number of digits are:1
#2:
4
the number of cases are:5
the current case is:1
the number of digits are:1
#2:
6
the number of cases are:5
the current case is:1
the number of digits are:1
#2:
7
the number of cases are:5
the current case is:1
the number of digits are:1
#2:
7
the number of cases are:5
the current case is:1
the number of digits are:1
#2:
8
the number of cases are:5
the current case is:1
the number of digits are:1
I've tried to understand why this happens, but I couldn't find the answer.
Thank you!
Upvotes: 0
Views: 38
Reputation: 1882
Number one, you haven't declared a string, you declared a character and treated it as a string, which is going to cause you all sorts of trouble. Probably why you are getting weird values. char x
should be char x[16]
or whatever the maximum length (in digits) of the number is, plus one, because strings end in the null character (0) in C. When you refer to this string, because it is an array of characters, you don't need the address operator &
(unless you want a pointer to the string instead of the string itself, say if you were passing it as an output from a function). printf("%c", *(&x + i))
is better and more clearly written as printf("%c",x[i])
or even putchar(x[i])
.
scanf
doesn't work well with user input. It is best to use fgets
for this purpose. This is also safer since fgets
takes a maximum length. Use stdin
for the FILE
argument. Be sure to check the return value; it will be the value NULL
when there is no more data. Typically this is when you press Control-D
key in Unix or Control-Z
key in Windows.
Upvotes: 2