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.
$ ./a.out Enter your full name : John Smit Full name : John
Scanf input till enterScanf 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.
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.
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.
./a.out #1: James Bond #2: John Smith
About our authors: Team EQA
You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.
Learn on Youtube