[英]In C, how do I only accept certain strings and continue to ask the user for input until valid input is entered?
[英]how to loop user input and copy it to file until “exit” string in entered using C?
我想編寫一個小程序,當最大輸入為100個字符時(使用控制台)從用戶那里獲取字符串,當用戶按下Enter鍵時,它將把輸入復制到某個文件中。 當用戶輸入字符串“ exit”時,我想退出循環
例如:“嗨,你好嗎?” “ bla bla”“退出”我只是不知道如何使它工作-我應該使用scanf嗎? getchar? fgets?
char* buf ;
int i;
buf = (char*)calloc(100, sizeof(char));
while(1)
{
fgets(s, sizeof(s), stdin);
if (strcmp(s , "exit") == 0)
break;
else
...write to file...
}
我需要手動輸入“ \\ 0”嗎?
謝謝!
fgets()
很好,但是在某些實現中,它將尾隨換行符( \\n
)放在行尾。 您必須刪除它才能使比較生效,或者准備進行比較以接受"exit"
和"exit\\n"
:
if (strcmp(s , "exit") == 0 || strcmp(s , "exit\n") == 0)
break;
要么
fgets(s, sizeof(s), stdin);
char *p = strchr(s, '\n');
if (p) *p = 0;
if (strcmp(s , "exit") == 0)
break;
旁注:除非您打算將字符串返回給調用者函數,否則根本不需要使用calloc()
。 改用自動數組:
char s[0x100]; // or whatever
我應該使用scanf嗎? getchar? fgets?
以上任何一項,但您的while
循環應轉換為:讀取輸入時,輸入不是“退出”。 您的while
循環當前轉換為:世界未盡。
我建議類似:
while (fgets(s, sizeof s, stdin) == s && strcmp(s, "exit\n") != 0) {
/* ... */
}
我需要手動輸入“ \\ 0”嗎?
沒有; 仔細選擇工具可以使您使用標准字符串庫處理由標准I / O庫生成的字符串(對於上面的fgets
/ strcmp
代碼而言),或通過其他更復雜的方法處理非字符串。
PS。 無需malloc
,並且sizeof (char)
在C中始終為 1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.