fgets(input,sizeof(input),stdin);
if (strcmp(input, "quit") == 0){
exit(-1);
}
如果我键入quit,它不会退出程式; 我想知道為什麼会這樣。
順便說一下
被宣佈為
input
char *input;
最新回復
- 5月前1 #
- 5月前2 #
函式
fgets
可能会在讀取的字元串末尾添加換行符.您必须檢查以下內容:size_t ln = strlen(input) - 1; if (input[ln] == '\n') input[ln] = '\0';
甚至
strtok(input, "\n");
- 5月前3 #
建議您將此代碼編碼為:
if(strstr(input, "quit") != NULL){
原因:這將解決人们添加額外字元(例如,文字之前或之後的空格)的問题。
- 5月前4 #
此解決方案仅需要標準庫(stdio.h)並给出相同的結果。< / p>
for (i = 0; input[i] != '\0'; i++); /* getting the string size */ input[i-1] = '\0'; /* removing the newline */
- 5月前5 #
我所做的是將換行符替換為'\ 0'null。
while(fgets(message,80,stdin)) { l=strlen(message)-1; if(message[l]='\n') message[l]='\0'; else message[i+1]='\0'; }
在輸入中跟蹤換行符.见老兄.測試"退出" +換行符,例如:
我完全錯過了最後一句话,re
char *input
.根据架構,input
將為4或8个位元組长.所以代碼很有效這並不能反映記憶體的實際大小,
input
指着.只要輸入少於八个位元組,這可能就可以了,但是如果輸入更大,則会截斷輸入.此外,下次呼叫fgets
時,您將获得其餘輸入。您應该给出實際大小,或者接受@JonathanLeffler的建議,然後宣告一个char陣列,例如
或