fork download
  1. #include <stdio.h>
  2. #include "readstring.h"
  3. /*
  4.   The function readstring reads n characters from
  5.   standard input and places them in the array s,
  6.   followed by a null terminator '\0'.
  7.  
  8.   s must have enough space to store n characters plus the null terminator
  9.  
  10.   More specifically readstring does the following:
  11.   -Skips any leading whitespace
  12.   -Reads up to n non-whitespace characters, storing them in s
  13.   -If there were more than n consecutive non-whitespace characters
  14.   on the input stream, readstring discards the remaining ones until
  15.   it finds whitespace or EOF
  16.   -readstring appends the null terminator \0 to the characters
  17.   that were read into s
  18.  
  19.   Returns 1 if it successfully read a string, 0 otherwise.
  20. */
  21.  
  22. int readstring(char *s, int n){
  23. int i = 0;
  24. scanf(" ");//Skip whitespace
  25. //While scanf reads one character, and we have not read too many,
  26. //and the character read was not white space, increase i:
  27. while(scanf("%c",&s[i]) == 1 && i < n && s[i] != ' ' && s[i] != '\n') {
  28. i++;
  29. }
  30.  
  31. if(!feof(stdin)) {
  32. //s[i] now holds the last character read (i.e. first character that should not be stored in s)
  33. //If s[i] is not white space,
  34. //continue reading until we find white space or EOF
  35. while(s[i] != ' ' && s[i] != '\n' && 1 == scanf("%c", &s[i])) {};
  36. }
  37.  
  38. //Replace s[i] with '\0' to null-terminate the string
  39. s[i] = '\0';
  40. //Return 1 if we managed to read a string, 0 otherwise.
  41. return i > 0;
  42. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp:2:24: error: readstring.h: No such file or directory
prog.cpp: In function ‘int readstring(char*, int)’:
prog.cpp:24: warning: ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result
stdout
Standard output is empty