这段代码有什么问题? [英] what is wrong in this code?
本文介绍了这段代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include<constream.h>
void main()
{
clrscr();
textmode(0);
char a[20];
for(int i=0;i<5;i++)
{
cin>>a[i];
}
for( i=0;i<5;i++)
{
cout<<a[i];
}
getch();
}
我正在尝试制作一个程序,该程序从用户那里获取5个名字并打印这些名称,但我没有得到正确的输出....当我运行程序但没有得到正确的输出时没有错误
I m trying to make a program which take 5 names from user and print these name but i m not getting the right output....there is no error when i m running the program but not getting the right output
推荐答案
可能你有cin缓冲问题。
但请注意,您使用的是古老的编译器和C
类似的字符串。我建议你得到一个更新的编译器(有许多免费提供)并使用std :: string
s而不是字符数组。
Probably you have a problem with cin buffering.
However, please note, you are using an ancient compiler andC
-like strings. I would suggest your to get a more up to date compiler (there are many freely available) and usestd::string
s instead of character arrays.
如果你的目标是用C ++编程(与C相反),你应该使用C ++方法。特别是,C ++具有从显式内存管理中抽象出来的各种容器。可能的解决方案可能是:
If you aim to program in C++ (in contrast to C), you should use C++ means. Especially, C++ has various containers that abstract from explicit memory management. A possible solution could be:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
vector<string> names;
while(true) {
cout << "Please enter a name (a dot ends asking for names): ";
string name;
cin >> name;
if (name == ".") break;
names.push_back(name);
}
for(auto it = names.begin(); it != names.end(); ++it) {
cout << "Name: " << *it << endl;
}
return 0;
}
干杯
Andi
Cheers
Andi
在第二个循环中你需要像这样定义一个变量i,它未在此范围中定义:
In the second loop you need to define a variable "i" like this, it is not defined in this scope :
//for( i=0;i<5;i++)
for(int i=0;i<5;i++)
{
cout<<a[i];
}
这篇关于这段代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文