【问题标题】:c++ object array string input is not working at console [duplicate]c ++对象数组字符串输入在控制台上不起作用[重复]
【发布时间】:2018-12-11 05:37:42
【问题描述】:

谁能解释为什么我在使用下面的 C++ 代码时遇到问题?

#include <iostream>
using namespace std;

class stud
{
public:    
    string name,adrs;     
    long long unsigned int  mob;
};

int main()
{
    stud s[10];
    unsigned int num;
    cout << endl << "Enter the number of students(<10): ";
    cin >> num;
    cout << endl;
    for(int i = 0; i < num; i++)
    {
        cout << endl << "Enter student " << i+1 << " name(put '.' at end and press enter): ";
        getline(cin, s[i].name);  // this line skips some data before even they are
                                  //entered and there is no error while compiling
    }
    system("CLS");
    for(int i = 0; i < num; i++)
    {
        cout << endl << " Student " << i+1 << " name is: ";
        cout << s[i].name << endl;
    }
    return 0;
}

当我尝试为上述数组中的对象输入字符串值时,使用不带任何分隔符的getline()(默认使用新行),我没有得到正确的输出,因为其他一些数据是自动的被跳过。

但是,当我使用getline() 而不是上面的方法时,它可以正常工作,但最后需要一个分隔符:

getline(cin, s[i].name, '.');

请帮我找到解决办法。我认为 Enter 键一次按下几次,这就是getline() 跳过一些数据的原因。不过,我不确定。

【问题讨论】:

  • 将问题发布为段落,而不是代码中的 cmets。正确缩进和格式化代码。
  • "我认为Enter 键在一次按下时被按下了多次" - 是什么让你这么认为? Enter 键通常不是这样工作的。 StackOverflow 不是调试服务。到目前为止,您为自己解决此问题做了哪些工作?您甚至尝试过使用调试器吗?为什么要求用户在名称末尾输入'.'getline() 默认情况下不需要这样做,那么简单地让用户输入 Enter 来结束名称有什么问题?

标签: c++ arrays object


【解决方案1】:

在纠正你的程序之前要知道的一件事是

实际上,当您从终端提交时选择 Enter 或 Return 时,总是会在您的输入中附加一个换行符。

cin>> 不会在用户按下 Enter 时从缓冲区中删除新行。

这与您自己提供的输入无关,而是与 std::getline() 表现出的默认行为有关。当您为名称提供输入时 (std::cin >> num;),您不仅提交了以下字符,而且还在流中附加了一个隐式换行符,getline() 将其误认为是用户输入和 enter。

如果您以后要使用 getline(cin,any string),建议在使用 cin>>(whatever) 之后使用 cin.ignore() 来删除那些多余的字符。 编辑这部分代码:

    stud s[10];
    unsigned int num;
    cout << endl << "Enter the number of students(<10): ";
    cin >> num;
    cout << endl;
    cin.ignore();//just add this line in your program after getting num value through cin
    //fflush(stdin);
    //cin.sync();
    //getchar();
    for(int i = 0; i < num; i++)
    {

        cout<<endl<< "Enter student " << i+1 << " name(put '.' at end and press enter): ";
        getline(cin,s[i].name);
    }
    system("CLS");

您也可以使用 fflush(stdin) 并且可能很想使用,但不推荐使用它,因为它具有未定义的行为,如 根据标准, fflush 只能与输出缓冲区一起使用,显然 stdin 不是其中之一。 关于 cin.sync():

在“cin”语句之后使用“cin.sync()”会丢弃缓冲区中剩余的所有内容。虽然“cin.sync()”并非在所有实现中都有效(根据 C++11 及以上标准)。

也可以使用getchar()来获取回车引起的换行

【讨论】:

  • 您的回答非常有帮助,先生和 cin.ignore() 有效,但作为 c++ 的初学者,我从未听说过 ignore() sync() 函数,并且在任何书籍或视频教程中都没有提到它,而教辛。您能否向我推荐一些高级网站/书籍,我可以在其中找到我所学的所有内容的“深度潜水”……这将非常有帮助,先生。
  • @ElectroVoyager:访问此链接:stackoverflow.com/questions/388242/…
  • @ElectroVoyager:关于网站,我认为目前最适合初学者的网站是 geeksforgeeks ,链接:geeksforgeeks.org/c-plus-plus
猜你喜欢
  • 2018-12-21
  • 2020-02-18
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多