C/Console/Scanf
Содержание
Convert temperatures
#include <stdio.h>
int main(){
int choice = 0;
double temperature = 0.0;
printf("Select the conversion (1 or 2): ");
scanf("%d", &choice);
printf("Enter a temperature in degrees %s: ",
(choice == 1 ? "Centigrade" : "Fahrenheit"));
scanf("%lf", &temperature);
if(choice == 1)
printf("That is equivalent to %.2lf degrees Fahrenheit\n", temperature*9.0/5.0+32.0);
else
printf("That is equivalent to %.2lf degrees Centigrade\n", (temperature-32.0)*5.0/9.0);
}
Pointer argument to scanf
#include <stdio.h>
void main() {
int value = 0;
int *pvalue = NULL;
pvalue = &value; /* Set pointer to refer to value */
printf ("Input an integer: ");
scanf(" %d", pvalue); /* Read into value via the pointer */
printf("\n Your enter is %d\n", value); /* Output the value entered */
}
Read formatted data from string
#include <stdio.h>
int main(void)
{
char str[80];
int i;
sscanf("hello 1 2 3 4 5", "%s%d", str, &i);
printf("%s %d", str, i);
return 0;
}
Reading characters with scanf()
#include <stdio.h>
void main()
{
char initial = " ";
char name[80] = { 0 };
char age[4] = { 0 };
printf("Your first initial: ");
scanf("%c", &initial );
printf("Your first name:" );
scanf("%s", name );
if(initial != name[0])
printf("\n%s,you got your initial wrong.", name);
else
printf("\nHi, %s. Your initial is correct.", name );
printf("\nYour full name and your age separated by a comma:\n" );
scanf("%[^,] , %[0123456789]", name, age );
printf("\nYour name is %s and you are %s years old\n", name, age );
}
Various read: string, float: scanf
#include <stdio.h>
int main(void)
{
char str[80], str2[80];
int i;
/* read a string and an integer */
scanf("%s%d", str, &i);
/* read up to 79 chars into str */
scanf("%79s", str);
/* skip the integer between the two strings */
scanf("%s%*d%s", str, str2);
return 0;
}