簡體   English   中英

scanf到fgets C

[英]scanf to fgets C

假設我需要輸入兩個名稱,例如[name name]\\n ...。(可能是更多的[name name]\\n 。假設名稱的長度為19,到目前為止,我的代碼是,我該如何防止例如[name name name]\\n input [name name name]\\n或更多[name name name...]\\n這樣的輸入?我聽說過fgets()和fscanf,但是有人可以給我示范一個如何使用它們的示例嗎? 。

char name1[20];
char name2[20];
for(int i=0; i < numberOfRow ; i++){
  scanf(" %s %s", name1, name2);
}

好的,所以我找到了一種確保只有兩個元素的方法,但是我不確定如何將它們放回變量中。

char str[50];
int i;
int count = 0;
fgets(str, 50, stdin);

i = strlen(str)-1;
for(int x=0; x < i ;x++){
  if(isspace(str[x]))
    count++;
}
if(counter > 1){
  printf("Error: More than 2 elements.\n");
}else if{
//How do i place those two element back into the variable ?
char name1[20];
char name2[20];

}

如果您要使用標准輸入,則無法停止它,用戶可以輸入他們喜歡的內容。 最好先讀所有輸入,然后再檢查然后輸入結果。

您可以使用fgets讀取所有行,然后解析結果。 例如:

char name[256];
for (int i = 0; i < numberOfRow; i++)
{
   if (fgets(name, 256, stdin) != NULL)
   {
      // Parse string
   }
}

fgets讀取該行,直到按Enter。 現在,您需要解析此字符串,如果用戶輸入錯誤的輸入(如“ aaa”或“ aaa bbb ccc”)返回錯誤,否則(“ aaa bbb”),請分割字符串並使用“ aaa”作為name1和“ bbb”作為name2

您可以使用strtok(string.h)。 請注意,此函數會修改您的源字符串(您可以在之前復制該字符串)。

strtok的示例:

char* word;

// First word:
word = strtok(str, " "); // space as the delimiter
strncpy(name1, word, sizeof(name1) - 1); 
name1[sizeof(name1) - 1] = 0;  // end of word, in case the word size is > sizeof(name1)    

// Second word
word = strtok (NULL, " ");
strncpy(name2, word, sizeof(name2) - 1);
name2[sizeof(name2) - 1] = 0;

另外,我認為你應該

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM