Using scanf()/scanf_s() to read formatted data from the standard input stream and sprintf()/sprintf_s() to write formatted data to a string

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows 2003 Server Standard Edition

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info:

To do: Using scanf()/scanf_s() to read formatted data from the standard input stream and sprintf()/sprintf_s() to write formatted data to a string

To show: How to use scanf()/scanf_s() and sprintf()/sprintf_s() to read formatted data from the standard input stream and to write formatted data to a string respectively

 

// Using scanf()/scanf_s()/wscanf() and sprintf()/sprintf_s()/swprintf()

#include <stdio.h>

 

int main(void)

{

char s[80];

int x;

float y;

 

printf("Using sprint()/sprintf_s()\n");

printf("---------------------------\n");

printf("Enter an integer and a float, separated by space: \n");

 

// scanf("%d%f", &x, &y); - using a secure version

scanf_s("%d%f", &x, &y);

 

// sprintf(s, "Integer:%6d\nFloat:%8.2f", x, y); using a secure version

sprintf_s(s, 80, "Integer:%6d\nFloat:%8.2f", x, y);

printf("\n%s\n%s\n", "The formatted output stored in array s is: ", s);

return 0;

}

 

Output example:

 

Using sprint()/sprintf_s()

---------------------------

Enter an integer and a float, separated by space:

210 20.15

The formatted output stored in array s is:

Integer: 210

Float: 20.15

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index