有没有更好的方法来打印最多 N 个字符的字符串? [英] Is there a better way to print a string with cout up to N characters?

查看:23
本文介绍了有没有更好的方法来打印最多 N 个字符的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

-edit- 我发送的是二进制文件而不是字符串.我的测试是使用 html 页面,所以在这个例子中我只使用了一个字符串,但我的问题是关于二进制、向量和使用 ostream 进行调试.我这样做可以消除一些混乱.

-edit- I am sending binary and not a string. My test is using html pages so in this example i am only using a string but my question is about binary, vectors and debugging with ostream. I make this clears some confusion.

我有以下代码:

cout << string(&v[0]).substr(0, len);

有没有更好的方法来打印字符串 v 并增加长度 len?我想做 v[len] = 0 但我抛出了一个大小为 1 的断言.我的代码是:

Is there a better way to print the string v with cout up the length len? I thought of doing v[len] = 0 but I an assertion is thrown with a size of 1. My code is:

vector<char> v;
v.reserve(1024*16); //required
v.resize(1); //so we can do &v[0]
recv(sockfd, &v[0], v.capacity(), 0);
while (l > 0)
{
    cout << string(&v[0]).substr(0, l);
    recv(sockfd, &v[0], v.capacity(), 0);
}
cout << "the size is " << v.size();

推荐答案

你可以在 cout 对象上使用 ostream::write 方法:

You can use the method ostream::write on the cout object:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
  vector<char> test;
  test.push_back('a');
  test.push_back('b');
  test.push_back('c');

  cout.write(&test[0], 3);
  cout << endl;
}

输出:

ABC

因为 ostream::write 返回一个 ostream&包含*this,你甚至可以做

Since ostream::write returns an ostream& containing *this, you can even do

cout.write(&test[0], 3) << endl;

但我不确定这实际上是否更好(或更清晰).

but I'm not sure that is actually any better (or clearer).

这篇关于有没有更好的方法来打印最多 N 个字符的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆