language: C++ 4.7.2 (gcc-4.7.2)
date: 426 days 17 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdio.h>
#include "readstring.h"
/*
  The function readstring reads n characters from 
  standard input and places them in the array s, 
  followed by a null terminator '\0'.
  
  s must have enough space to store n characters plus the null terminator
  
  More specifically readstring does the following:
  -Skips any leading whitespace
  -Reads up to n non-whitespace characters, storing them in s
  -If there were more than n consecutive non-whitespace characters 
   on the input stream, readstring discards the remaining ones until
   it finds whitespace or EOF   
  -readstring appends the null terminator \0 to the characters 
   that were read into s
 
  Returns 1 if it successfully read a string, 0 otherwise.
*/
  
int readstring(char *s, int n){
  int i = 0;
  scanf(" ");//Skip whitespace
  //While scanf reads one character, and we have not read too many,
  //and the character read was not white space, increase i:
  while(scanf("%c",&s[i]) == 1 && i < n && s[i] != ' ' && s[i] != '\n') {
    i++;
  }
  
  if(!feof(stdin)) { 
    //s[i] now holds the last character read (i.e. first character that should not be stored in s)
    //If s[i] is not white space, 
    //continue reading until we find white space or EOF
    while(s[i] != ' ' && s[i] != '\n' && 1 == scanf("%c", &s[i])) {};
  }
  
  //Replace s[i] with '\0' to null-terminate the string
  s[i] = '\0';
  //Return 1 if we managed to read a string, 0 otherwise.
  return i > 0;
}
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