2011-04-05 150 views
2

这是最好的连接方式?Const char * vs const wchar_t *(concatenation)

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

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

谢谢。

+2

什么是initError?另外如果你正在处理字符,你必须使用printf。是wchar_t类型的initError吗? – 2011-04-05 13:47:53

+0

你在找'wcstombs'吗? – Erik 2011-04-05 13:48:02

+0

如果我使用printf和fprintf,initError的类型也是const char * – Azodious 2011-04-05 13:49:56

回答

2

我认为正确的做法是:

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

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

但如果我使用带有味精的wprintf或fwprintf,它将不起作用。 – Azodious 2011-04-05 13:57:41

+0

@Azodious - std :: wcout会工作! – 2011-04-05 14:01:31

+0

@Azodious:如果你想使用c函数,使用'msg.c_str()'。 – Xeo 2011-04-05 14:44:56

1

你的大问题是,你混合数据类型。使用char及相关功能或wchar及相关功能。如果您需要混合它们,请使用转换功能。这不会比尝试将float传递给需要字符串的函数更有意义。 (编译器应该能够赶上这两个问题,因为wprintf声明是一样的东西int wprintf(const wchar_t *, ...)。)

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

而且,既然这是C++,那么使用std::string类会更好。这并不完美,但它比C风格的琴弦要好得多。

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