C++:格式不是字符串文字,也不是格式参数

Kam*_*ski -1 c++ stack char bison

我一直在尝试打印一个字符串文字,但似乎我做错了,因为我收到了编译警告.这可能是由于错误的格式化或我对c_str()功能的误解,我认为应该返回一个string.

parser.y: In function ‘void setVal(int)’:
parser.y:617:41: warning: format not a string literal and no format arguments [-Wformat-security]
Run Code Online (Sandbox Code Playgroud)

617行:

sprintf(temp, constStack.top().c_str());
Run Code Online (Sandbox Code Playgroud)

有这些声明

#include <stack>
const int LENGTH = 15;
char *temp = new char[LENGTH];
stack<string> constStack;
Run Code Online (Sandbox Code Playgroud)

如何为字符串提供正确的格式?

Ala*_*kes 10

简单 - 提供格式字符串:

sprintf(temp, "%s", constStack.top().c_str());
Run Code Online (Sandbox Code Playgroud)

但更好,更好:

string temp = constStack.top();
Run Code Online (Sandbox Code Playgroud)

  • 第二个版本至少比第一个版本少两个错误. (2认同)
  • @nobodynoone:这几乎没有意义.你很高兴使用`std :: string`作为`constStack.top()`,你只需要在接口点转换为`char*`,而不是你控件内的代码.我不确定如何成为"编译器项目"的理由. (2认同)