我想交互式
(我想)從標準輸入讀取一行直到EOF,但在每行之後如果行首字符是'+'
然後打印"OK"
其他打印"NOT OK"
。我試過這段代碼,但即使輸入的第一個字符的第一個字符等於'+'
,也會打印"NOT OK"
。從標準輸入讀取直到EOF並在測試第一個字符後打印文本
int main()
{
#define BUF_SIZE 1024
char buffer[BUF_SIZE];
size_t contentSize = 1;
/* Preallocate space. We could just allocate one char here,
but that wouldn't be efficient. */
char *content = malloc(sizeof(char) * BUF_SIZE);
if(content == NULL)
{
perror("Failed to allocate content");
exit(1);
}
content[0] = '\0'; // make null-terminated
while(fgets(buffer, BUF_SIZE, stdin))
{
char *old = content;
contentSize += strlen(buffer);
content = realloc(content, contentSize);
if(content == NULL)
{
perror("Failed to reallocate content");
free(old);
exit(2);
}
strcat(content, buffer);
if (content[0]== '+') {
printf("OK\n");
} else {
printf("NOT OK\n");
}
}
if(ferror(stdin))
{
free(content);
perror("Error reading from stdin.");
exit(3);
}
}
問題是?順便說一句,你的''鑰匙壞了嗎? – alk
是這個代碼打印不好,即使在第一個字符是'+' – mardon
OT:你能確定沒有輸入的行比1023'char's更長嗎? – alk