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; } |
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlICJyZWFkc3RyaW5nLmgiCi8qCiAgVGhlIGZ1bmN0aW9uIHJlYWRzdHJpbmcgcmVhZHMgbiBjaGFyYWN0ZXJzIGZyb20gCiAgc3RhbmRhcmQgaW5wdXQgYW5kIHBsYWNlcyB0aGVtIGluIHRoZSBhcnJheSBzLCAKICBmb2xsb3dlZCBieSBhIG51bGwgdGVybWluYXRvciAnXDAnLgogIAogIHMgbXVzdCBoYXZlIGVub3VnaCBzcGFjZSB0byBzdG9yZSBuIGNoYXJhY3RlcnMgcGx1cyB0aGUgbnVsbCB0ZXJtaW5hdG9yCiAgCiAgTW9yZSBzcGVjaWZpY2FsbHkgcmVhZHN0cmluZyBkb2VzIHRoZSBmb2xsb3dpbmc6CiAgLVNraXBzIGFueSBsZWFkaW5nIHdoaXR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luIHMpCiAgICAvL0lmIHNbaV0gaXMgbm90IHdoaXRlIHNwYWNlLCAKICAgIC8vY29udGludWUgcmVhZGluZyB1bnRpbCB3ZSBmaW5kIHdoaXRlIHNwYWNlIG9yIEVPRgogICAgd2hpbGUoc1tpXSAhPSAnICcgJiYgc1tpXSAhPSAnXG4nICYmIDEgPT0gc2NhbmYoIiVjIiwgJnNbaV0pKSB7fTsKICB9CiAgCiAgLy9SZXBsYWNlIHNbaV0gd2l0aCAnXDAnIHRvIG51bGwtdGVybWluYXRlIHRoZSBzdHJpbmcKICBzW2ldID0gJ1wwJzsKICAvL1JldHVybiAxIGlmIHdlIG1hbmFnZWQgdG8gcmVhZCBhIHN0cmluZywgMCBvdGhlcndpc2UuCiAgcmV0dXJuIGkgPiAwOwp9
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
-
result: Compilation error (maybe you wish to see an example for C++ 4.7.2)


