c语言中如何借用指针输出字符串?

如题所述

第1个回答  2022-12-11

使用指针输出字符串有以下几种方式:

1、使用printf 函数进行输出,其使用的格式转换符为%s,如 

char *str = "test";//指针指向一个字符串

printf ("%s\n", str);//输出str指向的字符串

2、使用puts函数进行输出,如

char *str = "test";

puts(str);//输出str指向的字符串,会自动多输出一个换行

3、使用自定义函数进行输出,如

void myPuts(char *str)//自定义输出函数

{

if (!str)return ;

while (*str != '\0'){

putchar(*str);

str++;

}

char *str = "test";

myPuts(str);

扩展资料:

C++指针与字符串

1、C语言里没有字符串数据类型,要想获得字符串的表示形式利用字符数组

#include<iostream>

using namespace std;

#include<stdlib.h>

void main()

{

char ar[]={'a','b','c','d'};

cout<<ar;   //字符串后无结束符\0,会有多余打印

cout<<endl;

char br[]={'a','b','c','d','\0'};

cout<<br;

cout<<endl;

char cr[5]="abcd";   //字符串结尾默认隐藏了\0

cout<<cr;

system("PAUSE");

}

2、C语言里没有字符串数据类型,要想获得字符串的表示形式利用字符指针

#include<iostream>

using namespace std;

#include<stdlib.h>

void main()

{

char *p="hello world";

cout<<p;   

//整形的指针,打印指针时只能打印其内部地址

//字符指针,打印指针时也是地址,但是这个被看作字符指针后,会打印该指针指向地址内存放的字符串,打印直到遇到\0为止

system("PAUSE");

}

3、静态常量区的字符串存储及指针访问

#include<iostream>

using namespace std;

#include<stdlib.h>

#include<string.h>

void main()

{

char *p="hello world";   //hello world存放在内存的静态常量区

//指针变量p存储的是该静态常量区的首个字符地址

//不能通过指针修改静态常量区的字符,但是可以通过指针访问

int length=strlen(p);   

//strlen计算的是字符串p的有效长度,不算\0

for(int i=0;i<length;++i)

{

cout<<p[i];

}

system("PAUSE");

}

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网