如何存儲使用空格輸入的字符串。 對於例如:字符串輸入使用換行可使用用於環路被存儲,然後被存儲到陣列中,同樣如何存儲其輸入爲一個單一的線串,但隨着空間存儲使用空格輸入的字符串
0
A
回答
1
使用fscanf
的%s
格式指令。它有一個字段寬度,如果你有興趣避免緩衝區溢出(你應該是),例如char foo[128]; int x = fscanf(stdin, "%127s", foo);
...不要忘記檢查x
。
在閱讀這樣一個固定寬度的字段後,需要進行一些錯誤檢查。如果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);
...
將單詞分配給數組的例子?無problemo:
不要忘記free(bar[0]); free(bar[1]); /* ... */
相關問題
- 1. 帶空格的C++輸入字符串
- 2. 帶空格的字符串輸入
- 3. 將輸入字符串存儲到C
- 4. C++存儲字符串輸入爲cstring
- 5. 輸出帶前導空格的字符串以保存空格
- 6. 嘗試使用空格輸入字符串時SQLite崩潰
- 7. C++,字母,數字和空格用戶輸入字符串
- 8. 存儲從用戶輸入的字符數組空間
- 9. 使用輸入用戶創建文件,使用帶空格的字符串(C)
- 10. 用Ints和字符串接受帶空格的輸入C
- 11. 在用戶輸入的字符串之間添加空格
- 12. 讀取字符串的所有輸入,用空格分隔
- 13. 將用戶輸入的日期字符串存儲爲datetime
- 14. 如何以空格作爲輸入字符串並存儲在java中的字符數組中
- 15. 在輸入字符串中輸入一定數量的字符時,甚至不存儲整個字符串
- 16. 使用Strtok存儲一串字符串
- 17. 如何在C++中用空格輸入長字符串?
- 18. 如何在存儲過程中修剪字符串的空格?
- 19. 如何使用掃描器在java中使用空格輸入字符串
- 20. 將用戶輸入存儲在字符串數組中?
- 21. C#在字符串數組中存儲用戶輸入
- 22. 如何在字符串中存儲用戶輸入?
- 23. 將用戶輸入作爲字符串存儲在JAVA中
- 24. MySQL字符串編碼存儲空間
- 25. Mysql - 插入帶空格的字符串
- 26. 可空INT輸入字符串的不正確的格式
- 27. 忽略數字,空格和讀取字符串輸入,使用Character.isLetter&Character.isDigit
- 28. 在輸入字段值中存儲JSON字符串
- 29. 輸入一個字符串後,防止字符串中出現空格
- 30. 檢查輸入字段中是否存在空字符串
可以使用的功能fgets和strtok的。 –
'scanf(「%s」,str)'在循環中? –
輸入後,我想將每個單詞存儲到數組中。 –