使用 fgets 讀取包含空格的字符串
// 使用 fgets 讀取包含空格的字符串
#include <stdio.h>
#include <string.h> int main() { char name[100]; printf("Enter your name: "); fgets(name, sizeof(name), stdin); // 移除可能讀取到的換行符 name[strcspn(name, "\n")] = 0; printf("Your name is %s.\n", name); return 0;
}
在以上的例子中,fgets 讀取一行輸入到 name 數組中,包括空格和換行符(如果輸入行太長,換行符會被存儲在數組中)。
然后,使用 strcspn 函數找到換行符的位置,并將其替換為空字符,以移除換行符。