prinf()和sanf()函数用于输入和输出,关于数据整型、字符型和浮点型此时对应的都是一个
scanf("%d",&i);
或者是
scanf("%c",&c);
又或者是
scanf("%f",&f);
如果遇到字符串,解决思路如下:
#include "stdafx.h"
#include <windows.h>
#include <string.h>
#define PRAISE "What a marvelous name!"
int _tmain(int argc, _TCHAR* argv[])
{
char name[40];
printf("What's your name?\n");
scanf("%s", name);
printf("Hello %s . %s\n", name, PRAISE);
printf("Your name of %d letters occupies %d memory cells.\n", strlen(name), sizeof(name));
system("pause");
return 0;
}
此时可以定义一个字符数数组。
#include "stdafx.h"
#include <windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
int i = 0,j=0,k=0,l=0;
char first_name[20], last_name[20];
printf("What's your first name?\n");
while ((*(first_name+i) = getchar()) != '\n')
{
i++;
}
printf("What's your last name?\n");
while ((*(last_name + j) = getchar()) != '\n')
{
j++;
}
printf_s("Your name is ");
while (i>0)
{
putchar(*(first_name+k));
k++;
i--;
}
while (j>0)
{
putchar(*(last_name + l));
l++;
j--;
}
system("pause");
return 0;
}
写循环将字符串一个一个读和写。显然直接运用前者。以后还会用到动态申请空间的情况。
经常遇到题目需要循环嵌套输入输出三角、倒三角
#include "stdafx.h"
#include <windows.h>
#include <string.h>
int _tmain(int argc, _TCHAR* argv[])
{
char c[26];
int j;
for (int i = 0; i < 26; i++)
{
for (j = 0; j <= 26-i; j++) printf(" ");
for (j = 0; j <= i; j++) printf("%c", 'A'+i);
//for (j = j - 1; j >0; j--) printf("%c", 'A' + j);
printf("\n");
}
system("pause");
return 0;
}
输出结果是
解题关键在于for循环的嵌套使用。
注意1:右边的三角,需要打印左边的空格printf(" ");