C語言中既然" "與空格『 』是不一樣的,那為什麼在字元串問題中,scanf中還不能讀入空格?
例如字元串"hello world",用scanf以%s格式輸入,只能輸出"hello",字元串是以『 』作為結尾,而『 』!=" "。
Reading Undelimited stringsscanf Width Specification
To read strings not delimited by whitespace characters, a set of characters in brackets ([ ]) can be substituted for the s (string) type character. The set of characters in brackets is referred to as a control string. The corresponding input field is read up to the first character that does not appear in the control string. If the first character in the set is a caret (^), the effect is reversed: The input field is read up to the first character that does appear in the rest of the character set.
因為是這樣設計的。
如果有讀取空格的需求,可以參考如下代碼。
#include &
int main()
{
char str[128];
scanf( "%[^
]", str );
printf( "%s
", str );
return 0;
}
這不是說明空格與 等價,而是由於C語言的緩衝機制,scanf讀取數據不是從鍵盤直接讀取,因為鍵盤是字元型輸入設備,且它是中斷方式來被操作系統控制,所以這些IO設備存取速率及其低下,而內存是塊設備,讀取速度非常快,因此引入緩衝區機制來緩衝IO設備與內存的數據交換,scanf也是從緩衝區地區,而scanf函數是把空格作為緩衝區數據的分隔符,每遇到一個空格,則表示當前一段數據為可用數據被scanf讀取,而不是空格表示字元結束而被讀入
推薦閱讀:
※這段python多進程百思不得其解,求大神指點問題何在?
※運行過程中程序中的變數存儲在哪?
※C++中已經有面向對象的概念,那struct還有啥存在的意圖?
※Python模塊如何安裝 並確認模塊已經安裝好?
※在編程中有沒有巧妙運用數學知識解決過問題?