看到簡化的代碼 - 我很困惑...printf()的困惑 - 印刷(空)時,試圖打印字符串,並打印緩衝區時,打印正確的值
#include <stdio.h>
#include <string>
#include <cstdlib> // includes the standard library and overarchs over stdlib.h
using namespace std;
void main()
{
char buffer[10];
string theString;
int i = 997799; //(simplified)
itoa(i,buffer,10);
theString = buffer;
printf("\n string is: %s of length %d \n", theString, theString.length());
printf("\n buffer is: %s of length %d \n", buffer, theString.length());
return;
}
我得到的輸出是意外:
string is: (null) of length 926366009
buffer is: 997799 of length 6
(1)爲什麼字符串打印爲空? (2)爲什麼theString.length()在第一個printf()中沒有正確打印,但在第二個中是正確的? (3)如果我在Visual Studio中設置了斷點,'buffer'顯示爲「997799」,而'theString'顯示爲{「997799」} - 這裏有一些奇怪的事情發生?
謝謝大家! 編輯我非常感謝提供答案的詳細程度 - 他們都更加清楚,並幫助我超越了我的問題 - 非常感謝你花幫忙:)
'void main'不合法。使用'int main'。 'itoa'不是標準功能。並且http://stackoverflow.com/questions/10865957/c-printf-with-stdstring – chris