-1

I'm a beginner in C programming so please be nice! I'm trying to solve some practice beginner challenges and the one I'm on at the moment needs me to capture text input. In the brief code below anything will be captured up to the 1st space. after this nothing appears whilst debugging.

I did try the gets instruction 1st but this wouldn't compile even though I'd followed examples online

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

int main(void) {
char stringcapture[500];
scanf("%s", stringcapture);

LongestWords(stringcapture);       
return 0;
}

So I'm trying to pass 'stringcapture' into the longestwords function. However all that gets captured and hence passed is the 1st word up to a space being entered

Robt800
  • 29
  • 7

1 Answers1

2

"%s" capture only word and the capture stop if a white space retrieved. So the capture will stop in the first space found that's why you got only 1 word Use the following pattern instead:

scanf("%[^\n\r]", str);

"%[^\n\r]" means capture all characters till retrieving "\r" or "\n"

To prevent your source code from buffer overflow you have to specify the maximum number of characters of the capture. Use the following pattern

char str[500];
scanf("%499[^\n\r]", str);
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 2
    In the case perhaps `fgets` might be better? Alternatively add the control for the maximum length of string. – Ed Heal Jun 11 '19 at 17:49
  • Thanks very much for the responses - looks like I have 2 options & they both work. Thanks for the help! – Robt800 Jun 12 '19 at 18:42