- 设计并测试一个函数,从输入中获取n个字符(包括空白、制表符、换行符),把结果储存在一个数组里,它的地址被传递作为一个参数。
#include <stdio.h>
#define LIM 10
void string_gets(char *st, int n);
int main(int argc, char const *argv[])
{
char str[LIM];
puts("Enter:");
string_gets(str, LIM);
puts("Output:");
puts(str);
return 0;
}
void string_gets(char *st, int n) //n为最大字符
{
int i;
for ( i = 0; i < n - 1; i++ ) // 预留'\0'空间
{
scanf("%c", (st + i));
}
*(st + i) = '\0';
}
/*
输出结果:
Enter:
abc def
ghi
Output:
abc def
g
*/
}
2.修改并编程练习1的函数,在n个字符后停止,或在读到第1个空白、制表符或换行符时停止,哪个先遇到哪个停止。不能只使用scanf()。
#include <stdio.h>
#define LIM 10
void string_gets(char *st, int n);
int main(int argc, char const *argv[])
{
char str[LIM];
puts("Enter:");
string_gets(str, LIM);
puts("Output:");
puts(str);
return 0;
}
void string_gets(char *st, int n) //n为最大字符
{
int i = 0;
while ( i < n && (st[i] = getchar()) != ' ' && st[i] != '\t' && st[i] != '\n' )
{
i++;
}
*(st + i) = '\0';
}
/*
输出结果:
Enter:
abc efg
Output:
abc
*/
3.设计并测试一个函数,从一行输入中把一个单词读入一个数组中,并丢弃输入行中的其余字符。该函数应该跳过第1个非空白字符前面的所有空白。将一个单词定义为没有空白、制表符或换行符的字符序列。
#include <stdio.h>
#define LIM 10
void string_gets(char *st);
int main(int argc, char const *argv[])
{
char str[LIM];
puts("Enter:");
string_gets(str);
puts("Output:");
puts(str);
return 0;
}
void string_gets(char *st)
{
int ch;
while ( (ch = getchar()) == ' '); //跳过第1个非空白字符前的所有空白【可用<ctype.h>中的isspace函数检查空白字符】
st[0] = ch; //当读取到第1个非空白字符时会被略过,由原本需要接收字符的st[0]来接收
do
{
st++;
} while ((*st = getchar()) != ' ' && *st != '\t' && *st != '\n' );
*st = '\0';
while ( getchar() != '\n' ) //跳过剩余缓冲区的字符
{
continue;
}
}
/*
输出结果:
Enter:
abc efg
Output:
abc
*/
4.设计并测试一个函数,它类似编程练习3的描述,只不过它接受第2个参数指明可读取的最大字符数。
#include <stdio.h>
#define LIM 10
void string_gets(char *st, int n);
int main(int argc, char const *argv[])
{
char str[LIM];
puts("Enter:");
string_gets(str, LIM);
puts("Output:");
puts(str);
return 0;
}
void string_gets(char *st, int n)
{
int ch;
int i = 0;
while ( (ch = getchar()) == ' '); //跳过第1个非空白字符前的所有空白【可用<ctype.h>中的isspace函数检查空白字符】
st[0] = ch; //当读取到第1个非空白字符时会被略过,由原本需要接收字符的st[0]来接收
do
{
i++; //判定条件n-1,预留'\0'的空间
} while ( i < (n - 1) && (st[i] = getchar()) != ' ' && st[i] != '\t' && st[i] != '\n' );
*(st + i) = '\0';
while ( getchar() != '\n' ) //跳过剩余缓冲区的字符
{
continue;
}
}
/*
输出结果:
Enter:
1234567890 qwe
Output:
123456789
*/
5.设计并测试一个函数,搜索第1个函数形参指定的字符串,在其中查找第2个函数形参指定的字符首次出现的位置。如果成功,该函数返指指向该字符的指针,如果在字符串中未找到指定字符,则返回空指针(该函数的功能与strchr()函数相同)。在一个完整的程序中测试该函数,适应一个循环给函数提供输入值。
#include <stdio.h>
char *string_strchr(const char *st, char ch);
int main(int argc, char const *argv[])
{
char str1[] = "HelloWord";
char ch;
char *str2;
do
{
printf("To stop, press the Enter key at a line's start.\n"); //输入回车即结束
scanf("%c", &ch);
str2 = string_strchr(str1, ch);
if( str2 ) //如果str2不为NULL,即打印
{
puts(str2);
}else
{
puts("Not found");
}
while ( (ch != '\n') && (getchar() != '\n') ) //过滤掉scanf留下的‘\n’;
{
continue;
}
} while ( ch != '\n' );
puts("Bye!");
return 0;