C++练习中的一些问题

cheliangzhang 2019-01-26 02:14:45
为什么输入两三个字符,可以继续,输入六七个字符的字符串就会失败呢?
#include<iostream>
#include<ctime>
struct donation
{
char name[20];
double dons;
};
int main()
{
int ps;
std::cout << "Enter the numbers of donation:";
std::cin >> ps;
donation * donor = new donation[ps];
for (int i = 0; i < ps; i++)
{
std::cout << "Enter the #" << i+1 << " donator's name:";
std::cin.getline((donor + i)->name,20);
//std::cin.clear();
std::cin.get();
std::cin.get();
//std::cin.get();
std::cout << "Enter the #" << i+1 << " donations:";
std::cin.get();
std::cin.get();
std::cin>>((donor + i)->dons);

}
std::cout << "Grand Patrons:" << std::endl;
int count = 0;
int i = 0;

while (i<=ps)
{
if ((donor + i)->dons > 10000)
{
std::cout << (donor + i)->name[20] << " " << (donor + i)->dons << std::endl;
count++;
}
i++;
}

delete[] donor;
int secs = 10;
clock_t delay = secs * CLOCKS_PER_SEC;
clock_t start = clock();
while (clock()-start<delay)
{
;
}
std::cin.get();
std::cin.get();
return 0;
}
...全文
121 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
独孤过 2019-01-27
  • 打赏
  • 举报
回复
在std::cin.getline之前抵消回车产生字符

for (int i = 0; i < ps; i++)
{
	std::cin.get();
	std::cout << "Enter the #" << i + 1 << " donator's name:";
	std::cin.getline((donor + i)->name, 20);
	std::cout << "Enter the #" << i + 1 << " donations:";
	std::cin >> ((donor + i)->dons);
}
赵4老师 2019-01-26
  • 打赏
  • 举报
回复
乍看起来c++的cin、cout、ifstream、ofstream、istringstream、ostringstream在输入、输出上比c的scanf、printf、fscanf、fprintf、fread、fwrite、sscanf、sprintf简单,不用格式控制符!
但是不用格式控制符,输入输出恰好是你期望的格式的时候好说;等到输入输出不是你期望的格式的时候,你就会觉得还是用格式控制符更方便、更靠谱。
摒弃cin、cout、ifstream、ofstream、istringstream、ostringstream!
使用scanf、printf、fscanf、fprintf、fread、fwrite、sscanf、sprintf。

64,682

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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