Skip to content

Instantly share code, notes, and snippets.

@napthink
Last active October 22, 2016 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save napthink/1e9bf43ac03ad5b074984d4f414fa881 to your computer and use it in GitHub Desktop.
Save napthink/1e9bf43ac03ad5b074984d4f414fa881 to your computer and use it in GitHub Desktop.
Cで標準入力から文字列を読み取る関数とその使用例のサンプルコード
#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;
}
@napthink
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment