读入字符串给用户,直到“。”用来

时间:2012-09-15 15:19:00

标签: c string input user-input stdin

我对如何实现代码的这一部分感到有些困惑。

我需要从用户读入一个最多可包含256个字符的字符串。如果用户输入字符串,该字符串还应包含任何间距和换行符。当用户单独输入"."时,它将告诉程序输入已完成。输入完成后,程序将使用相同的间距和换行符反射完全相同的字符串。

例如:

Please enter a string: This is just a test.
The input has not ended yet.
It will end when the user enters just a period.
.

程序返回:

This is just a test.
The input has not ended yet.
It will end when the user enters just a period.

到目前为止,我能想到这样做的唯一方法是使用fgets(),但我不太确定在使用"."完成输入时如何进行检查。我在考虑可能需要不断检查的循环?

任何帮助将不胜感激。 谢谢!

1 个答案:

答案 0 :(得分:1)

我们的想法是使用一个缓冲区,每当有新数据进入时你都会重新分配,并跟踪它的大小:

char* data = NULL;
size_t size = 0;

你的假设是正确的,你需要一个循环。像这样:

int end = 0;
while (!end) {
    char buf[512];
    if (fgets(buf, sizeof buf, stdin) == NULL) {
        // an error occured, you probably should abort the program
    }
}

您必须检查缓冲区是否实际上是您想要结束数据输入的令牌:

if (strcmp(buf, ".\n") == 0) {
    // end loop
}

如果找不到令牌,则需要重新分配数据缓冲区,按照刚才读取的字符串长度将其加长:

size_t len = strlen(buf);
char* tmp = realloc(data, size + len + 1);   // ... plus the null terminator
if (tmp == NULL) {
    // handle your allocation failure
}

...并在最后复制新内容:

data = tmp;
memcpy(data + size, buf, len);
size += len;
data[size] = '\0';                           // don't forget the null terminator

完成后,输出并清理:

printf("%s", data);
free(data);

填写空白,组装,你将有一个可行的,安全的程序,可以满足你的要求。