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

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

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

在读取这样的固定宽度字段后,需要进行一些错误检查。 如果fscanf读取最大字符数,则需要停止读取…很可能会在流上留下一些非空格字符,应使用以下内容将其丢弃: fscanf(stdin, "%*[^ \n]"); 。 您可能还想让用户知道他们的输入已被截断。

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

 #include  #include  #include  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);

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

 char *bar[42] = { 0 } bar[0] = get_dynamic_word(stdin); bar[1] = get_dynamic_word(stdin); /* ... */ 

别忘了free(bar[0]); free(bar[1]); /* ... */ free(bar[0]); free(bar[1]); /* ... */