简体   繁体   中英

scanf to fgets C

Say I need to read in two name like, [name name]\\n .... (possibly more [name name]\\n . Assuming the name can have length of 19, my code so far is, How would I actually prevent an input like [name name name]\\n or more [name name name...]\\n in my case ? I heard about fgets() and fscanf but would anyone kindly show me an example how to use them? Thanks in advance.

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

Ok So I found a way to make sure there is only two element, but I am not sure how to put them back into variable...

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];

}

If you are going from standard input, there is no way of stopping this, the user can enter what they like. It would be preferable to read in all the input first then check then result.

You can use fgets to read all the line, and then parse the results. for example:

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

fgets reads the line, until Enter is pressed. Now you need to parse this string, if user enter wrong input (as "aaa" or "aaa bbb ccc") return error, else ("aaa bbb"), split the string and use "aaa" as name1 and "bbb" as name2

You can use strtok (string.h). Please be careful, this function will modify your source string (you may copy the string before).

Example for 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;

Also, I think you should chec

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM