我想交互式
(我想)从标准输入读取一行直到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