2017-07-07 57 views
1

例如,如果我使用以下命令:有没有什么办法可以知道在C++中输出到标准输出的大小?

cout << "hello world"; 

有没有办法知道的精选被打印到stdout什么规模?

+1

在什么单位?人物,像素还有其他什么? –

+5

这似乎是一个XY问题。你为什么需要知道?并非所有类型都实现“大小”,并且实际数据可以通过提供'operator <<'重载来序列化,这是由标准库为字符串完成的。 –

+0

您可以通过两步完成,从数据中构建一个字符串,测量它,然后将其打印出来,然后执行任何您需要的操作。一个例子是你想要将可变长度的数据安排到列中,但是你不知道列的需求。在决定其大小之前,您需要在每列中找到最长的项目。你可以尝试解释你的用例以获得更好的建议。 –

回答

1

我怀疑是否有一个标准的方法来确定写入标准输出之前要写入多少字节。

你可以做的是,把它写到ostringstream并获得流的大小。这加倍的工作,但给你一个标准的通用方法,以确定有多少字节写入时流将对象采取:

template <class T> 
std::size_t stream_len(const T& t) 
{ 
    std::ostringstream oss; 
    oss << t; 
    return oss.tellp(); 
} 

这里是一个演示:http://coliru.stacked-crooked.com/a/3de664b4059250ae

7

您可以使用std::stringstream这个:

#include <sstream> 
#include <iostream> 

int main(){ 
    std::stringstream ss; 
    int a = 3; 
    ss<<"Hello, world! "<<a<<std::endl; 
    std::cout<<"Size was: "<<ss.str().size()<<std::endl; 
    std::cout<<ss.str()<<std::endl; 
} 

以上的回报16:14字符的 “Hello,world!” 的,对于变量a内容1个字符,并从std::endl一个字符。

+0

这可能是一个矫枉过正,如果你输出一个ascii字符串,就像你的例子中没有'endl'。你可以用'strlen'或'string.length()'来测量它的长度 – Serge

0

这里是一个老学校C风格的方式,仍然是有效的C++以及现代C++:

#include <iostream> 

int main() { 
    // C style but still valid c++ 
    std::cout << "C style but still valid C++\n"; 
    char phrase[] = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' }; 
    char phrase2[] = { "hello world" }; 

    // Adding 1 for the new line character. 
    std::cout << "size of phrase[] in bytes = " 
       << sizeof(phrase) 
       << " + 1 for newline giving total of " 
       << sizeof(phrase) + 1 
       << " total bytes\n"; // Not Null terminated 

    std::cout << "size of phrase2[] in bytes = " 
       << sizeof(phrase2) 
       << " + 1 for newline giving total of " 
       << sizeof(phrase2) + 1 
       << " total bytes\n"; // Null terminated 

    // Or you can do it more c++ style 
    std::cout << "\nC++ style\n"; 
    // Also adding one for newline character and this string is not null terminated 
    std::cout << "size of string in bytes = " 
       << std::string("hello world").size() 
       << " + 1 for newline giving a total of " 
       << std::string("hello world").size() + 1 
       << " total bytes\n"; 

    std::cout << "Press any key and enter to quit." << std::endl; 
    char c; 
    std::cin >> c; 

    return 0; 
} 

由于在C/C++每个字符为1个字节;所有你需要的是包括特殊字符(如空格,空终止符,换行符等)的字符数。这就是为什么在C/C++中有sizeof(Type) operator

输出

C style but still valid C++ 
size of phrase[] in bytes = 11 + 1 for newline giving total of 12 total bytes 
size of phrase2[] in bytes = 12 + 1 for newline giving total of 13 total bytes 

C++ style 
size of string in bytes = 11 + 1 for newline giving a total of 12 total bytes 
Press any key and enter to quit. 

现在这样只会让你的输出的大小,你将其发送到ostream'scout对象之前。这也不反映描述此输出的文本的添加字符。

正如其他人说你可以使用stringstream来连接一串字符串,字符和其他数据类型与insertion operator <<stringstream对象,然后让stream's成员函数给你的大小bytes

它的工作方式与std::string(...).size()相同。

相关问题