0

I'm writing a code and I need to be able to input 2 int values and a line of numbers with spaces inbetween so I wrote:

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

int main()
{
    int L, X;
    char lin[25] = {};
    scanf("%d", &L);
    scanf("%s", &lin);
    scanf("%d", &X);
    return 0;
}

In console I input the first number(L) and that works but when the second scanf for the string is supposed to happen it just skips it(as seen in the debugger) and assigns the first number I wrote in the line to the X variable. Also locals tab shows first line of string lin is usually '\n' and I dont think its from my keyboard sending double the amount of signals when I press that key. I tried using fgets(lin, 25, stdin) but it does the same thing.

Does anyone have an idea how to take input of int, string (of numbers and spaces for characters) and the int in that order?

I tired to take input of int, string (of numbers and spaces for characters) and the int in that order

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Can you show an example of the input you're giving? – Steve Summit Nov 23 '22 at 20:21
  • It's a good idea to (a) always check `scanf`'s return value to ensure that it succeeded and (b) always print a prompt before each `scanf` call. Without those it can be *very* hard to know which call is doing what as it runs. – Steve Summit Nov 23 '22 at 20:21
  • Not your problem, but: `scanf("%s", &lin);` is wrong. It should be `scanf("%s", lin);`. – Steve Summit Nov 23 '22 at 20:23
  • You might find [these `scanf` guidelines](https://stackoverflow.com/questions/72178518#72178652) useful. – Steve Summit Nov 23 '22 at 20:24
  • If you want to read and process lines of input, you're often *much* better off reading each of those lines using `fgets`. If a particular line contains numbers you need as, say, integers, you can convert them as a second step, using functions like `atoi`, `strtol`, or `sscanf`. – Steve Summit Nov 23 '22 at 20:47

1 Answers1

0

If you want to read a string with embedded spaces then instead of this call

scanf("%s", &lin);

write

scanf( " %24[^\n]", lin);

Pay attention to two details. In your call of scanf the type of the second argument expression &lin is incorrect. The function expects an argument of the type char * while you are passing an argument of the type char ( * )[25].

And see the leading space in the format string of the provided example of scanf. It allows to skip white space characters as for example the new line character '\n' that is stored in the buffer after pressing the key Enter after the preceding call of scanf.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335