const char * 与 const wchar_t* (串联)

发布于 2024-10-30 07:55:42 字数 231 浏览 8 评论 0原文

这是最好的连接方式?

const char * s1= "\nInit() failed: ";
const char * s2 = "\n";
char buf[100];
strcpy(buf, s1);
strcat(buf, initError);
strcat(buf, s2);
wprintf(buf);

它给出了错误。正确的方法应该是什么?

谢谢。

which is the best way to concat?

const char * s1= "\nInit() failed: ";
const char * s2 = "\n";
char buf[100];
strcpy(buf, s1);
strcat(buf, initError);
strcat(buf, s2);
wprintf(buf);

It gives error. What should be the correct way?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

﹎☆浅夏丿初晴 2024-11-06 07:55:42

我认为正确的方法是:

std::string msg = std::string("Init() Failed ") + initError + "\n";
std::cout<<msg;

或者

std::cout<<"Init() Failed "<<initError<<"\n";

I think the correct way is:

std::string msg = std::string("Init() Failed ") + initError + "\n";
std::cout<<msg;

or

std::cout<<"Init() Failed "<<initError<<"\n";
趁年轻赶紧闹 2024-11-06 07:55:42

你的大问题是你混合了数据类型。使用 char 和关联函数或 wchar 和关联函数。如果需要混合它们,请使用转换函数。这并不比尝试将浮点数传递给需要字符串的函数更有意义。 (编译器应该能够捕获这两个问题,因为 wprintf 的声明类似于 int wprintf(const wchar_t *, ...)。)

另一个更小的问题,问题是 printf 等不是打印一般字符串的正确函数,因为如果字符串中有任何百分号,您将得到未定义的行为。使用 printf("%s",...)puts(...) 或相关函数。

而且,由于这是 C++,因此最好使用 std::string 类。它并不完美,但比 C 风格的字符串要好得多。

另外,告诉我们错误是什么也会有所帮助。您甚至没有告诉我们这是编译器错误还是运行时错误。

Your big problem is that you're mixing data types. Use either char and associated functions or wchar and associated functions. If you need to mix them, use a conversion function. This makes no more sense than trying to pass a float to a function needing a string. (The compiler should be able to catch both problems, since the declaration of wprintf is something like int wprintf(const wchar_t *, ...).)

Another, more minor, issue is that printf and such are not the right functions to print out general strings, since if there are any percent signs in the strings you'll get undefined behavior. Use printf("%s",...) or puts(...) or related functions.

And, since this is C++, you'd be much better off using the std::string class. It isn't perfect, but it's far better than C-style strings.

Also, telling us what the error is would help. You haven't even told us whether it's a compiler error or a run-time error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文