存储使用空格输入的字符串

时间:2015-07-04 07:31:27

标签: c string

如何存储使用空格输入的字符串。 例如:使用换行输入的字符串可以使用for循环存储然后存储到数组中,类似地如何存储作为单行输入但带有空格的字符串

1 个答案:

答案 0 :(得分:1)

使用fscanf的{​​{1}}格式指令。如果你有兴趣避免缓冲区溢出(你应该这样做),它有一个字段宽度,例如%s ...不要忘记检查char foo[128]; int x = fscanf(stdin, "%127s", foo);

在读取这样一个固定宽度字段后,需要进行一些错误检查。如果x读取最大字符数,则需要停止读取...很可能会在流上留下一些非空格字符,应使用以下内容将其丢弃:{{1} }。您可能还想让用户知道他们的输入已被截断。

或者,如果您想阅读非常大的未知长度的单词,您可以使用我写的这个函数:

fscanf

示例:fscanf(stdin, "%*[^ \n]");不要忘记#include <ctype.h> #include <stdio.h> #include <stdlib.h> char *get_dynamic_word(FILE *f) { size_t bytes_read = 0; char *bytes = NULL; int c; do { c = fgetc(f); } while (c >= 0 && isspace(c)); do { if ((bytes_read & (bytes_read + 1)) == 0) { void *temp = realloc(bytes, bytes_read * 2 + 1); if (temp == NULL) { free(bytes); return NULL; } bytes = temp; } bytes[bytes_read] = c >= 0 && !isspace(c) ? c : '\0'; c = fgetc(f); } while (bytes[bytes_read++]); if (c >= 0) { ungetc(c, f); } return bytes; } ...

为数组分配单词的示例?没问题:

char *foo = get_dynamic_word(stdin);

不要忘记free(foo);