[英]scanf() method does not working in while loop?
我已經離開這個循環 5 個小時了。 我的 scanf 方法不起作用。
這是我的循環。
我無法執行庫的 strcmp 所以我自己寫了。
int string_compare(char str1[], char str2[])//Compare method
{
int ctr=strlen(str1);
int ctr2=strlen(str2);
int counter=0;
if(strlen(str1)!=strlen(str2) ){//if their lengths not equal -1
return -1;
} else
{
for (int i = 0; i < strlen(str1); ++i)
{
if(str1[i]==str2[i]){ //looking for their chars
counter++;
}
}
if(counter==strlen(str1)){
return 0;
} else
{
return -1;
}
}
}
char str1[100]; //for users command
char newString[10][10]; //after spliting command i have
while(string_compare(newString[0],"QUIT") != 0){
printf("Enter Commands For Execution\n");
scanf("%10[0-9a-zA-Z ]s\n",str1);
int i,j,ctr;
j=0; ctr=0;
for(i=0;i<=(strlen(str1));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(str1[i]==' '||str1[i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
} else
{
newString[ctr][j]=str1[i];
j++;
}
}
if(string_compare(newString[0],"QUIT") == 0){
printf("Quitting\n");
break;
}
if(string_compare(newString[0],"MRCT") == 0){
printf("hey\n");
}
if(string_compare(newString[0],"DISP") == 0){
printf("hey2\n");
}
}
當我執行我的 c 文件時,
循環要求我輸入諸如“MRCT”之類的命令。
它永遠打印
Enter Command
hey
Enter Command
hey
我使用scanf()
方式在這里不起作用。
scanf()
在第一次失敗后停止掃描。
所以在這里:
scanf("%10[0-9a-zA-Z ]s\n",str1);
掃描試圖解釋三件事:
%[]
到一個變量str1
s
請注意,如果字符串長度為零,它將在字符串處失敗,並且不會解釋s
或\\n
字符。
一:我懷疑s
是一個錯誤,你不想要它。
二:不要用"%[^\\n]\\n"
來讀一行。 如果該行為空(只有\\n
字符),則會失敗。
if (scanf("%10[0-9a-zA-Z ]", str1) == 1)
{
// Always check that the value was read.
// Then deal with it.
....
}
scanf("%*[^\n]"); // Ignore any remaining character above 10.
// Note this may still fail so don't add \n on the end
// Deal with end of line separately.
char c;
if (scanf("%c", &c) == 1 && c == '\n') // Now read the end of line character.
{
// End of line correctly read.
}
使用: scanf("%[^\\n]\\n" , str1);
使用scanf
函數獲取一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.