0

I am a complete beginner in C and am having trouble reading details from a user. I have a function called getDetails and this is what's in it.

char firstName[MAX];
char lastName[MAX];
int idIn;
int number;

printf("First name: ");
scanf("%s \n", firstName);
int len = strlen(firstName);
firstName[len - 1] = '\0';

printf("Last name: ");
scanf("%s \n", lastName);
int len2 = strlen(lastName);
lastName[len2 - 1] = '\0';

printf("ID: ");
scanf("%d \n", &idIn);
printf("Number: ");
scanf("%d \n", &number);

MAX is defined as 100.

I get to enter first and last name but then it just skips the rest. I really can't see why this is happening either.

John O C
  • 11
  • 5
  • 1
    @klutt not exactly, `%s` and `%d` both skip leading whitespace ... but this code here shows a complete cluelessness about `scanf()` format strings. –  Oct 24 '17 at 14:18
  • @klutt I thought that also first, but there is no scanf("%c") in the code and the scanf strings all contain ' ' and '\n'. – Werner Henze Oct 24 '17 at 14:18
  • Get rid of the "\n" s in the `scanf` s. – phoxis Oct 24 '17 at 14:19
  • Quick fix: remove all the ` \n` from the format strings. Still very buggy (at least add a field length to `%s`). –  Oct 24 '17 at 14:19
  • True. I retracted the flag. However, I'm pretty sure there's an appropriate duplicate. – klutt Oct 24 '17 at 14:20
  • Remove space character and \n from all `scanf()`. – H.S. Oct 24 '17 at 14:21
  • I'm voting to close here as simply removing the "clutter" from the `scanf()` format strings solves the immediate problem –  Oct 24 '17 at 14:21
  • 1
    @JohnOC in general, you should read at least a [`scanf()` manual](https://linux.die.net/man/3/scanf) and [How to read / parse input in C? The FAQ](https://stackoverflow.com/q/35178520/2371524). You might also be interested in my [beginners' guide away from `scanf()`](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html) –  Oct 24 '17 at 14:23
  • Please provide also some input example - how do you test this to see if it's working. this may shed some light. – zmii Oct 24 '17 at 14:23

1 Answers1

0

Tested and working Fine

#include <stdio.h>
#include <string.h>

int main()
{
   char arr[100];
   char rra[100];
   int idIn;
   int number;

   printf("First name: ");
   scanf("%99s", arr);
   int len = strlen(arr);
   //firstName[len - 1] = '\0';

   printf("Last name: ");
   scanf("%99s",rra);
   int len2 = strlen(rra);
   //lastName[len2 - 1] = '\0';

   printf("ID: ");
   scanf("%d", &idIn);
   printf("Number: ");
   scanf("%d", &number);
   return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
User
  • 31
  • 5