C语言
输入:
整型
int a; scanf("%d", &a);
长整型
long long b; scanf("%ld", &b);
浮点型
float c; scanf("%f", &c);
双精度
double d; scanf("%lf", &d);
长双精度
long double e; scanf("%lf", &e);
字符
char c; scanf("%c", &c);
或
char c; getchar(c);
字符串
char str[100]; scanf("%s", str);
或
char str[100]; gets(str);
混合输入
int f; double g; scanf("%d%lf", &f, &g); //空格格开 scanf("%d,&lf", &f, &g); //逗号格开
注意:c语言可以按宽度来输入的,如:
double h; scanf("%5lf", &h); //按小数点后五位输入
输出:
整型
printf("%d\n", a);
长整型
printf("%lld", &b);
浮点型
printf("%f\n", &c);
双精度
printf("%lf\n", &d);
长双精度
printf("%llf", &e);
字符
printf("%c\n", c);
或
putchar(c);
字符串
printf("%s\n", str);
或
puts(str);
按宽度输出(不带填充)
printf("%18d\n", a); //输出一个宽度为18的整型
按宽度输出(左填充)
printf("%18*d\n", a); //输出一个18位的整形,左填充*
按宽度输出(右填充)
printf("%-18*d", a); //输出一个18位的整形,右填充*
混合输出
printf("%d %lf\n", f, g); //空格格开 printf("%d, %lf\n", f, g); //逗号格开
带提示的输出
printf("你要输出的数是:%d", a);
C++
输入:
C++的输入比较容易,所有的输入都可以使用以下的方法:
cin >> [variable];
如输入一个整型
int num; cin >> num;
也可以混合输入
int num; double num1; cin >> num >> num1;
特别注意:
字符的输入
char c = cin.get();
或
char c; cin >> c;
字符串的输入
char str[100]; cin >> str; //不能有空格
char str[100]; cin.getline(str);
char str[100]; cin.getline(str, 100);
string类(在头文件string下)
string str; cin >> str; //不能有空格
string str; getline(cin,str); // 可以有空格
输出:
C++的输出也比较容易,所有的输出都可以用以下的方法:
std::cout << [variable];//如果在开头加了using namespace std;就可以不写std;
如输出一个变量num
cout << num << endl; //endl为换行
混合输出:
如:输出一个double变量d和一个int变量num
cout << d << " " << num << endl; //空格格开
带提示的输出
cout << "这个数的值为:" << num << endl;
方法一:使用ostream类的方法
按宽度输出(不带填充)
cout.width(18) << num;
按宽度输出(左填充)
cout.fill('*'); cout.width(18); cout.right<< num; //输出一个18位的整形,左填充*
按宽度输出(右填充)
cout.fill('*'); cout.width(18); cout.left << num; //输出一个18位的整形,右填充*
方法二:使用头文件ionaip
按宽度输出(不带填充)
cout << setw(18) << num << endl; //输出一个宽度为18的整型
按宽度输出(左填充)
cout << right << setw(18) << setfill('*') << num << endl; //输出一个18位的整形,左填充*
按宽度输出(右填充)
cout << left << setw(18) << setfill('*') << num << endl; //输出一个18位的整形,右填充*