Search code examples
cvalidationscanffgets

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

}


Solution

  • 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