-1

From previous threads, I know that you can achieve this by using the method shown here: How do you allow spaces to be entered using scanf?

It works in Main but when I put it inside a function, it doesn't work.

This is my code:

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

void dataInput();
struct record {
    char title[50];
    char author[50];
    char category[20];
    float price;
}; 

struct record info[500];

void main(){
    dataInput();
}

void dataInput(){
    int x;
    for(x = 0; x <= 10; x++ ){
        scanf("%s", &info[x].title);
        printf("%s\n", &info[x].title);
    }
}

Output:

Output1

If I use regex:

scanf("%50[0-9a-zA-Z ]s", &info[x].title);

Output:

Output2

Hmm whats wrong here

Community
  • 1
  • 1

4 Answers4

1

I haven't got the most robust reference manual by hand, but from Wikipedia:

%s : Scan a character string. The scan terminates at whitespace. A null character is stored at the end of the string, which means that the buffer supplied must be at least one character longer than the specified input length.

So %s does very different things in scanf and printf, and will in fact only read one word in scanf, whereas in printf it will yield the null terminated content pointed to.

Felix Frank
  • 8,125
  • 1
  • 23
  • 30
  • 1
    "%s : Scan a character string", well _almost_. In C, a string is an array of `char` up to and including the `'\0'`. `"%s"` informs `scanf()` to 1) scan in and discard leading white-space, 2) scan in `char` until a white-space is encountered 3) unget that white-space for subsequent I/O 4) If any non--write-space was scanned append an `'\0'` to the destination. Curiously if a rare `'\0'` is scanned, it is treated as a non-white-space character and scanning continues. – chux - Reinstate Monica Jun 14 '14 at 14:05
1

Your problem is pretty much explained here:

http://www.cplusplus.com/reference/cstdio/scanf/

For the %s format you have this:

Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.

That is why when you using a regex the problem disappears.

Cristina
  • 1,991
  • 3
  • 17
  • 24
1

Try

scanf("%[^\n]", &info[x].title);
MegaMind
  • 653
  • 6
  • 31
0
scanf (" %[^\n]%*c", &info[x].title);

Notice that there is a SPACE before %[, this will work correctly

illright
  • 3,991
  • 2
  • 29
  • 54