如何正确替换sprintf与<<操作者

时间:2014-07-15 05:56:40

标签: c++ visual-c++ printf cout

原帖:sprintf(buffer, "section%d rows", x + 1);

我的专栏:buffer << "section" << (x + 1) << " rows";

编译器抱怨,

  

表达式必须具有整数或枚举类型。

如果需要,请考虑以下声明?

char buffer[SIZE]; // SIZE is 128, here is the buffer I want to read into

更新:x是一个整数!

2 个答案:

答案 0 :(得分:3)

char []没有&lt;&lt;&lt;&lt;&lt;&lt;&lt;以您正在寻找的方式运作的运营商。尝试使用stringstream或其他流类。 http://www.cplusplus.com/reference/sstream/stringstream/

答案 1 :(得分:2)

以下是一个例子:

#include <iostream>
#include <sstream>
#include <cstring> // for memcpy

using namespace std;

int main()
{
    stringstream ss;
    ss << "test: " << 10 << " !";
    char buf[128];
    memcpy(buf, ss.str().c_str(), ss.str().size() + 1); // to include '\0'
    cout << buf << endl;
}

在这里,您需要使用memcpy复制到缓冲区。