[英]Error while trying to take multiple inputs in a switch inside a loop statement
[英]Trying to take multiple string inputs
實踐
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ARR 32
int main(void){
int MEM=64;
char arr[ARR],*p=(char *)calloc(MEM,(sizeof(char))),*q=NULL;
int i=0,j=1;
printf("\nEnter String : ");
while(j){
scanf(" %[^\n]s " ,arr);
if(j==1)
strcpy(p,arr);
else
strcat(p,arr);
if((j*ARR)==MEM){
MEM=MEM+(j*ARR);
q=realloc(p, MEM);
if(!(q)){
printf("\nNOT ENOUGH MEMORY\n");
goto END;
}
p=q;
}
for(i=0;i<(strlen(arr));++i){
if(arr[i]=='\n')
break;
}
if(arr[i]=='\n')
break;
++j;
}
printf("\n %s\n",p);
END: free(p);p=NULL;q=NULL;
return 0;
}
我正在嘗試獲取多個字符串輸入。
我正在使用scanf(" %[^\\n]s",arr);
接受輸入而不是fgets(arr,ARR,stdin);
,因為使用fgets
,一旦我按ENTER key
程序就會停止執行。 但是用scanf(" %[^\\n]s",arr);
即使輸入\\n
,程序也無法退出while() loop
。
我想知道編寫代碼時遇到的一個或多個錯誤。
讀取C語言中多行輸入的規范方法是在循環中使用fgets
,例如
while (fgets(arr, sizeof(arr), stdin) != NULL)
{
if (arr_contains_special_input_to_exit_loop(arr))
break;
// Optionally check for and remove trailing newline from input
// Append `arr` to your data
}
退出循環的條件可能是某些特殊輸入或空行或完全其他的東西。
一個錯誤是:
for(i=0;i<(strlen(arr));++i){
if(arr[i]=='\n')
break;
}
在您的代碼的前面,您有:
scanf(" %[^\n]s " ,arr);
[^\\n]
防止任何換行符\\n
包含在arr
。 因此,尋找(arr[i]=='\\n')
的循環將永遠找不到。 接下來的代碼繼續尋找不存在的newlines
:
if(arr[i]=='\n')
break;
最后一個break
也突破了外部循環,阻止您在查找換行符時要求輸入更多信息(不應這樣做)。 解決這些問題后,它應該會更進一步,允許您輸入多個項目。
編輯:
通過一點努力查看您正在做什么,我現在讓它接受多個輸入並根據需要重新分配。 字符串全部串聯起來並在末尾打印。 它仍然可以承受一些工作,但這應該給您一些提示:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ARR 32
int main (void) {
int MEM = 64;
char arr[ARR], *p = (char *) calloc (MEM, (sizeof (char))), *q = NULL;
int i = 0, j = 1;
while (j) {
printf ("\nEnter String : ");
scanf (" %[^\n]s ", arr);
printf (" you entered (arr): %s\n", arr);
if (strcmp (arr, "q") == 0) {
printf ("\n 'q' entered, exiting.\n\n"); // provide for exit if `q` entered
break;
}
if (j == 1)
strcpy (p, arr);
else
strcat (p, arr);
if ((j * ARR) == MEM) {
MEM = MEM + (j * ARR);
q = realloc (p, MEM);
if (!q) {
printf ("\nNOT ENOUGH MEMORY\n");
goto END;
}
else
printf ("\nMemory Reallocation - succeeded.\n");
p = q;
}
++j;
}
printf (" %s\n", p);
END:
if (p) free (p); /* always test pointer before calling free */
p = NULL;
q = NULL;
return 0;
}
輸出:
./bin/me
Enter String : fishinsea
you entered (arr): fishinsea
Enter String : alligators
you entered (arr): alligators
Memory Reallocation - succeeded.
Enter String : really_big_mosters
you entered (arr): really_big_mosters
Enter String : SuperSnake_Prudhome
you entered (arr): SuperSnake_Prudhome
Memory Reallocation - succeeded.
Enter String : 8_puppies
you entered (arr): 8_puppies
Enter String : q
you entered (arr): q
'q' entered, exiting.
fishinseaalligatorsreally_big_mostersSuperSnake_Prudhome8_puppies
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.