C语言具有允许在程序中输入和输出的标准库。 C中的stdio.h或标准输入输出库,具有用于输入和输出的方法。
scanf()
C语言中的scanf()方法按照指定的类型从控制台读取值。
句法:
scanf(“%X”, &variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable
and
& is the address operator in C, which tells the compiler to change the real value of this variable, stored at this address in the memory.
printf()
C语言中的printf()方法在控制台屏幕上打印作为参数传递给它的值。
句法:
printf(“%X”, variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable
and
& is the address operator in C, which tells the compiler to change the real value of this variable, stored at this address in the memory.
如何在C中进行基本类型的输入和输出?
C中的基本类型包括int,float,char等类型。为了输入或输出特定类型,上述语法中的X随该类型的特定格式说明符而改变。
这些输入和输出的语法为:
- 整数:
Input: scanf("%d", &intVariable); Output: printf("%d", intVariable);
- 漂浮:
Input: scanf("%f", &floatVariable); Output: printf("%f", floatVariable);
- 字符:
Input: scanf("%c", &charVariable); Output: printf("%c", charVariable);
有关更多示例,请参见C中的格式说明符。
// C program to show input and output
#include
int main()
{
// Declare the variables
int num;
char ch;
float f;
// --- Integer ---
// Input the integer
printf("Enter the integer: ");
scanf("%d", &num);
// Output the integer
printf("\nEntered integer is: %d", num);
// --- Float ---
// Input the float
printf("\n\nEnter the float: ");
scanf("%f", &f);
// Output the float
printf("\nEntered float is: %f", f);
// --- Character ---
// Input the Character
printf("\n\nEnter the Character: ");
scanf("%c", &ch);
// Output the Character
printf("\nEntered integer is: %c", ch);
return 0;
}
Enter the integer: 10
Entered integer is: 10
Enter the float: 2.5
Entered float is: 2.500000
Enter the Character: A
Entered integer is: A
如何在C中进行高级类型的输入和输出?
C语言中的高级类型包括String之类的类型。为了输入或输出字符串类型,使用%s格式说明符更改了以上语法中的X。
String的输入和输出的语法为:
Input: scanf("%s", stringVariable);
Output: printf("%s", stringVariable);
例子:
// C program to show input and output
#include
int main()
{
// Declare string variable
// as character array
char str[50];
// --- String ---
// To read a word
// Input the Word
printf("Enter the Word: ");
scanf("%s\n", str);
// Output the Word
printf("\nEntered Word is: %s", str);
// --- String ---
// To read a Sentence
// Input the Sentence
printf("\n\nEnter the Sentence: ");
scanf("%[^\n]\ns", str);
// Output the String
printf("\nEntered Sentence is: %s", str);
return 0;
}
Enter the Word: GeeksForGeeks
Entered Word is: GeeksForGeeks
Enter the Sentence: Geeks For Geeks
Entered Sentence is: Geeks For Geeks