为什么循环不允许输入名字? [英] Why can't loop allow to enter 1st name ?

查看:101
本文介绍了为什么循环不允许输入名字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  int  main()
{
int 长度;
cout<< 输入名称编号:;
cin>>长度;
string * names = new string [length];
// cout<< \ n names =<< names;
for int i( 0 ); i< length; i ++)>
{
cout<< \ n输入<< i + 1<< name:;
getline(cin,names [i]);
}

return 0 ;
}

解决方案

我之前的回复不正确。



问题是 cin 只读取第一个空白字符的下一个标记。在这种情况下,空格是数字后面的行尾字符,需要在第一次调用 getline 之前消耗。您可以通过调用 cin.get()清除输入缓冲区。



此外,您无法输入名称由于相同的原因包含空格(空格充当标记分隔符),因此您必须使用 getline 来读取整个字符串。


< blockquote>你有问题

 cin>>长度; 



将行终止符留在缓冲区中。



输入 cin 有点棘手,无论如何,快速解决方法是在它吃掉线路终结器之前立即添加 cin.ignore(); 。 br />

 cin>>长度; 
cin.ignore();







顺便说一下, Richard 给了你使用 vector< string> 而不是明确动态分配数组的好建议。事实上,在您的代码中,您永远不会释放已分配的内存。


int main()
{
    int length;
    cout << "Enter the no. of names: ";
    cin >> length;
    string *names = new string[length];
    //cout << "\n names= "<<names;
    for (int i(0);i<length;i++)>
    {
        cout << "\nEnter "<<i+1<<" name: ";
        getline(cin,names[i]);
    }
    
    return 0;
}

解决方案

My previous response was incorrect.

The issue is that cin only reads the next token up to the first whitespace character. In this case the whitespace is the end of line character(s) after the number, which need to be consumed before the first call to getline. You can clear the input buffer by calling cin.get().

Also, you cannot input a name containing spaces for the same reason (the space acts as a token delimiter), so you have to use getline to read the entire string.


You have a problem with

cin >> length;


leaving the line terminator in the buffer.

Input with cin is a bit tricky, anyway, a quick fix would be adding cin.ignore(); immediately before it to eat up the line terminator.

cin >> length;
cin.ignore();




By the way, Richard gave you the good advice of using vector<string> instead of explicitely dynamically allocated array. As matter of fact, in your code you never release the allocated memory.


这篇关于为什么循环不允许输入名字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆