【发布时间】:2014-01-27 06:21:54
【问题描述】:
查看简化代码 - 我很困惑...
#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 中设置断点,“缓冲区”显示为“997799”,而“theString”显示为 {“997799”} - 这里发生了什么奇怪的事情?
谢谢各位! 编辑我非常感谢所提供答案的详细程度 - 它们都增加了清晰度并帮助我解决了我的问题 - 非常感谢您花时间提供帮助:)
【问题讨论】:
-
void main不合法。使用int main。itoa不是标准函数。还有stackoverflow.com/questions/10865957/c-printf-with-stdstring