Last active
October 22, 2016 13:16
-
-
Save napthink/1e9bf43ac03ad5b074984d4f414fa881 to your computer and use it in GitHub Desktop.
Cで標準入力から文字列を読み取る関数とその使用例のサンプルコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<string.h> | |
#include<stdlib.h> | |
#define STS_ERROR 1 | |
#define STS_NORMAL 0 | |
int getStr(char *buffer, int size); | |
int main(void) { | |
char buffer[64]; | |
while(1) | |
{ | |
printf("> "); | |
if (getStr(buffer, sizeof(buffer)) == STS_ERROR) { | |
printf("too long..\n"); | |
continue; | |
} | |
if (strcmp(buffer, "q") == 0) | |
{ | |
printf("see you.\n"); | |
break; | |
} | |
printf(buffer); | |
printf("\n"); | |
} | |
} | |
/* | |
* 文字列の入力を受け付ける関数 | |
* @param | |
* buffer 文字列を格納するバッファ | |
* size 最大読み込みサイズ | |
* @return 1: エラー, 0: 正常終了 | |
*/ | |
int getStr(char *buffer, int size) { | |
char *pReturnPosition; //改行文字の位置 | |
fgets(buffer, size, stdin); | |
//改行文字を検索 | |
pReturnPosition = strchr(buffer, '\n'); | |
//読み残しあり | |
if (pReturnPosition == NULL) { | |
//標準入力をクリア | |
while(getchar() != '\n'); | |
return STS_ERROR; | |
} | |
//改行文字を削除 | |
*pReturnPosition = '\0'; | |
return STS_NORMAL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://hk0.hatenablog.com/entry/2016/08/13/000537