C++:const char * 到 stringstream

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5188140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:37:08  来源:igfitidea点击:

C++: const char * to stringstream

c++

提问by user459811

Is it possible to put a const char* into a string stream?

是否可以将 const char* 放入字符串流中?

I think it's possible with the write() function in stringstream but I'm having trouble figuring out how to get the streamsize if i only know of the const char *.

我认为 stringstream 中的 write() 函数是可能的,但是如果我只知道 const char * ,我就无法弄清楚如何获得流大小。

Assuming size is my const char * variable:

假设大小是我的 const char * 变量:

stringstream s;
s.write(temp,size);

How do I get size? Thanks.

我如何获得尺寸?谢谢。

回答by fpointbin

I tested it, and it works correctly...

我测试过,它工作正常......

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    stringstream s;
    const char* token = "HELLO";
    s << token;
    cout << s.str() << endl;
    return 0;
}

[facu@arch ~]$ g++ p.cpp 
[facu@arch ~]$ ./a.out 
HELLO

回答by dappawit

I may not be understanding correctly, but I think you're asking how to get the size of a char*string. To do that, all you need is strlen(str)which is in the <cstring>header. The string must be null terminated, though.

我可能没有正确理解,但我认为您是在问如何获取char*字符串的大小。要做到这一点,你需要的是strlen(str)这是在<cstring>报头。但是,该字符串必须以空字符结尾。

回答by fpointbin

I don't know if it is the best way to answer your question, but see:

我不知道这是否是回答您问题的最佳方式,但请参阅:

std::string _getline_ ( const char *str, const unsigned int ui_size )
{
    std::string tmp;
    unsigned short int flag = 0;
    while ( flag < 2 )
    {
    if( *str != '##代码##' )
    {
        tmp.push_back( *str );
        flag = 0;
    }
    else
    {
        tmp.push_back( ' ' );
        flag++;
    }
    str++;  
    }
    return tmp;
}

The problem is that "flag" will store two of "\0" no more... I don't know what is your proposite.. But i hope it will be useful for you... Maybe someone wanna fix it...

问题是“flag”将不再存储两个“\0”......我不知道你的提议是什么......但我希望它对你有用......也许有人想修复它...... .