Scanf string format

Scanf takes a string input through the formatting string "%s". This formatting character is not suitable for our purpose. We will see how our program scans the string and gives output.

#include <stdio.h>

int main(int argc, char *argv[])
{
  char string[20];
  printf("Enter your full name : ");
  scanf("%s", string);
  printf("Full name : %s\n", string);
  return 0;
}

Output

$ ./a.out
Enter your full name : John Smit
Full name : John

Scanf input till enter

Scanf works fine when the string has no space character inside it. Above output shows scanf has terminated the scan once space has been found in the buffer.

We often require to take input of full name, address and other fields where we have spaces inside the input. To deal with these situation we can scan the entire line of string and terminate the scanning when user presses enter or return. We should use "%[^\n]", which tells scanf() to take input string till user presses enter or return key.

#include <stdio.h>

int main(int argc, char *argv[])
{
  char string[20];
  printf("Enter your full name : ");
  scanf("%[^\n]", string);
  printf("Full name : %s\n", string);
  return 0;
}

Output

Scanf scans till user presses enter or till user presses return key.

./a.out
Enter your full name : John Smith
Full name : John Smith

File sting scan

Like console input fscanf can be used to scan strings in a text file. fscanf behaves in the same way as scanf. This below example scans full names from a text file. names.txt file contains full names in each line. Here full names scanf string scans only till space character.

#include <stdio.h>

int main(int argc, char *argv[])
{
  char string[20];
  int i = 0;
  FILE *fp;
  fp = fopen ("names.txt", "r");
  while(fscanf(fp, "%s", string) > 0)
  {
    printf("#%d: %s\n", i + 1, string);
    i++;
  }
  fclose(fp);
  
  return 0;
}

Output

Like console input with scanf, fscanf can be utilized to scan strings. Fscanf behaves in the same way as scanf. Fscanf terminates at space character.

cat names.txt
James Bond
John Smith

./a.out
#1: James
#2: Bond
#3: John
#4: Smith

File line by line iteration

We have a requirement to scan an entire line of text from a file. Like scanning till enter or return key is pressed we can use this same formatting for file operations also. This formatting "%[^\n]" can be used to scan an entire line from a file.

#include <stdio.h>

int main(int argc, char *argv[])
{
  char string[20];
  int i = 0;
  FILE *fp;
  fp = fopen ("names.txt", "r");
  while(!feof(fp))
  {
    fscanf(fp, "%[^\n]\n", string);
    printf("#%d: %s\n", i + 1, string);
    i++;
  }
  fclose(fp);
  
  return 0;
}

Output

./a.out
#1: James Bond
#2: John Smith

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#