如何输出指定长度的字符串?

LeafBoy 2004-06-10 09:37:11
比如我有一个字符串缓冲区,我只是想输出前几个字符串,比如

char buf[] = "hello, world";
std::cout << buf;

以上代码会输出hello, world,如果想输出hello,应该怎么做?

在C语言中,可以用printf("%5s", buf)来实现,但是使用C++的流对象如何控制呢?
...全文
866 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Wolf0403 2004-06-11
  • 打赏
  • 举报
回复 2
下面公布正确答案:

cout.write(buf, 5);

哈哈——
什么叫做简洁明了,什么叫做紧凑高效,什么叫做完美无暇……
【完美废人一手叉腰一脚踏在电脑主机上,哈哈大笑呈樱木花道状……】
jp1984 2004-06-10
  • 打赏
  • 举报
回复
#include <iostream>

#include <stdlib.h>

using namespace std;

int main(int argc, char *argv[])
{
char buf[]="hello,world!";

// char* p=buf;

int size;
cout<<"how many characters you wanna get:"<<endl;
//get the size...
cin>>size;

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

{cout<<buf[i];}

system("PAUSE");
return 0;
}//:)
complayer 2004-06-10
  • 打赏
  • 举报
回复
iostream有相关的操控器。
bm1408 2004-06-10
  • 打赏
  • 举报
回复
agree up!
bluebohe 2004-06-10
  • 打赏
  • 举报
回复
char buf[] = "hello, world";
buf[5]=0;
std::cout << buf;

24,860

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧