const char * 与 const wchar_t* (串联)
这是最好的连接方式?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为正确的方法是:
或者
I think the correct way is:
or
你的大问题是你混合了数据类型。使用
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 orwchar
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 ofwprintf
is something likeint 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. Useprintf("%s",...)
orputs(...)
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.