The reason why your getname
works is but getrno
doesn't is because of pass-by-reference vs. pass-by-value semantics and because arrays, like s1
decay to pointers. These are important concepts to understand if you want to program in C.
Think of it like this: When you call getname
it accepts a local copy of the address of a buffer. The function then writes into the buffer itself. But when you call your getrno
the function accepts a local copy of an integer and reads the value into that local copy, so that nothing changes in the program outside.
@askmish has proposed a good solution, but I would strongly advise something like this instead:
// getrno will prompt the user to enter the rno and will store it into the variable
// pointed to by b. If the function returns 1 then a value was successfully read.
int getrno(int* b)
{
// make sure that the pointer looks valid
if (b == NULL)
return 1;
// prompt the user to enter the text
puts ("enter the rno: ");
// Note the use of a single space at the beginning of the format string
// which is used to consume any whitespace (including return characters
// that might be present)
if (scanf (" %d", b) == 1)
return 0;
// We couldn't read one integer. Return an error.
return 1;
}
int main()
{
int x;
if (!getrno (&x))
printf ("rno = %d\n", x);
else
printf ("failed to get rno!");
return 0;
}
You ask how to go about doing floating-point numbers. The solution is to write a function which accepts, as necessary, either a float
or a double
pointer and which then calls scanf
with the correct format specifier, to read the value into that pointer. This function would look very much like the getrno
I showed you above.