求解为啥跳不出第一个for

sinat_37785686 2017-10-29 11:20:42
#include <iostream>
#include <new>
struct chaff
{
char dross[20];
int slag;
};
int attact()
{
return sizeof(chaff);
}
const int Arsize = 3*attact();
int main()
{
using namespace std;
char place[Arsize];
chaff *first = new(place) chaff[2];
cout << (void *)place << endl;
for(int i = 0; i < 2; i++){
cout << first + i * attact()<< endl;
cout << "Input the data:\n";
cout << "The string:";
cin.getline((first + i * attact())->dross,20);
cout << "The num:";
(cin >> (first + i * attact())->slag).get();
cout << i << endl;
}
cout << "Quit success\n";
for(int i = 0; i < 2; i++){
cout << first + i * attact()<< endl;
cout << "Input the data:\n";
cout << "The string:";
//cin.getline((first + i * attact())->dross,20);
cout << (first + i * attact())->dross << endl;
cout << "The num:";
cout << (first + i * attact())->slag << endl;
}
return 0;
}

我pc运行的输出:

0x6ffdb0
0x6ffdb0
Input the data:
The string:stringone
The num:1
0
0x6ffff0
Input the data:
The string:stringtwo
The num:2

--------------------------------
Process exited after 13.1 seconds with return value 3221225477
请按任意键继续. . .
...全文
240 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
x_xx_xxx_xxxx 2017-10-30
  • 打赏
  • 举报
回复
我只改了第一个循环,第二个循环,你自己改一下吧
x_xx_xxx_xxxx 2017-10-30
  • 打赏
  • 举报
回复
楼主,我运行了一下你的程序。错不在getline, 第一条回复是我的错。你错在把指针用错了,我改了过来,你看一下。 你计算数组内的地址不用在首地址加上数组元素真实大小来计算,只是加上它的序列位置,编译器会自动帮你计算。第二次循环的时候,数组越界,就报错了。 for(int i = 0; i < 2; i++) { cout << first + i << endl; //修改 cout << "Input the data:\n"; cout << "The string:"; cin.getline((first + i )->dross,20); //修改 cout << "The num:"; (cin >> (first + i )->slag).get(); //修改 cout << "i = " << i << endl; }

#include <iostream>
#include <new>
struct chaff
{
char dross[20];
int slag;
};
int attact()
{
return sizeof(chaff);
}
const int Arsize = 3*attact();
int main()
{
using namespace std;
char place[Arsize];
chaff *first = new(place) chaff[2];
cout << (void *)place << endl;
for(int i = 0; i < 2; i++)
{
	cout << first + i  << endl;
	cout << "Input the data:\n";
	cout << "The string:";
	cin.getline((first + i )->dross,20);
	cout << "The num:";
	(cin >> (first + i )->slag).get();
	cout << "i = " << i << endl;
}
cout << "Quit success\n";
for(int i = 0; i < 2; i++)
{
	cout << first + i * attact()<< endl;
	cout << "Input the data:\n";
	cout << "The string:";
//cin.getline((first + i * attact())->dross,20);
	cout << (first + i * attact())->dross << endl;
	cout << "The num:";
	cout << (first + i * attact())->slag << endl;
}
return 0;
}

x_xx_xxx_xxxx 2017-10-30
  • 打赏
  • 举报
回复
预计 getline 出错。 参考: http://blog.csdn.net/sunshine_in_moon/article/details/46638175?_t=t http://blog.sina.com.cn/s/blog_60263c1c0101ck25.html
大米粥哥哥 2017-10-29
  • 打赏
  • 举报
回复
建议设置断点调试调试

15,440

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧