Presentation is loading. Please wait.

Presentation is loading. Please wait.

sscanf()- string scan function

Similar presentations


Presentation on theme: "sscanf()- string scan function"— Presentation transcript:

1 sscanf()- string scan function
consumes data from a memory resident buffer instead of consuming data from a file. requires a format string to provide the formatting parameters for the data. sscanf( ) returns the number of items it successfully consumed from the buffer.

2 sscanf()- string scan function
General format: int sscanf(char *str, const char* format_str, …);

3 sscanf()- string scan function
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { char buffer[80]; char month[20]; char greet[15]; char str[90] = "Hello "; int day; int year; int nextYear; int width; int height; int area; int val[5];

4 sscanf()- string scan function
/* Using sscanf to format command line arguments */ if(argc < 3) { fprintf(stdout, "Expected: %s width height\n", argv[0]); exit(1); } sscanf(argv[1], "%d", &width); sscanf(argv[2], "%d", &height); area = width * height; fprintf(stdout, "\ndimensions: %d x %d, area: %d\n", width, height, area);

5 sscanf()- string scan function
/** Using sscanf to parse an input string . fgets stores input in a character string. must convert numeric characters to decimal values before using in a computation. sscanf can do the conversion. **/ fprintf(stdout, "Enter date (mm-string dd yyyy): "); fgets(buffer, 80, stdin); sscanf(buffer, "%s %d %d", month, &day, &year); nextYear = year + 1; // performs arithmetic on year fprintf(stdout, "\nDates\n"); fprintf(stdout, "%s %d, %d\n", month, day, year); fprintf(stdout, "%s %d, %d\n", month, day, nextYear);

6 sscanf()- string scan function
/** Using sscanf to parse a string str is initialized above. sscanf converts the numeric data to decimal values using %d **/ sscanf(str, "%s %d %d %d", greet, &val[0], &val[1], &val[2]); fprintf(stdout, "\n%s\n", greet); fprintf(stdout, "val[0]: %d\n", val[0]); fprintf(stdout, "val[1]: %d\n", val[1]); fprintf(stdout, "val[2]: %d\n\n", val[2]); return 0; }


Download ppt "sscanf()- string scan function"

Similar presentations


Ads by Google