为什么getline函数在if语句中不起作用? [英] Why the getline function is not working in if statement ?

查看:101
本文介绍了为什么getline函数在if语句中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我正在编写以下代码,则在运行时该代码不要求字符串,并且仅采用number的值,为什么呢?

if i am writing the following code then at run time the code is not asking for the string and it takes only the value of number, why it is?

#include<iostream.h>
#include<fstream.h>
#include<conio.h>

class x
{
      char ch[30];
      int num;
      public:
             void getdata()
             {
                  cout<<"Enter string";
                  cin.getline(ch,30);
                  cout<<"Enter a number :";
                  cin>>num;    
             }
};

int main()
{
    x o;
    int choice;
    cout<<"Enter your choice 1 for getdata and 2 to exit";
    cin>>choice;
    if(choice==1)
                 o.getdata();
    else
                 exit(0);
    getch();
    return 0;
}



[edit]添加了代码块,并进行了html编码-OriginalGriff [/edit]



[edit]Code block added, html encoded - OriginalGriff[/edit]

推荐答案

这可能是由于某些内容在流中留下了"\ n"程序的其他部分.在使用getline()之前冲洗流. chandanadhikari提出的建议绝对正确.尝试使用cin.ignore()或cin.sync和cin.clear,您的问题将得到解决.
This may be due to a ''\n'' left in the stream from some other part of your program. Flush the stream before using getline(). What chandanadhikari suggested is absolutely right. Try using cin.ignore() or cin.sync and cin.clear ,your problem will be solved.
class x
{
      
	
        char ch[30];
        int num;
        public:
	
             void getdata()
             {
				 
	         cout<<"Enter string:\n";
                  cin.ignore(); 
		getline(cin,s);
                  cout<<"Enter a number :";
                  cin>>num;    
				  
             }
};



在cin.getline()之前使用cin.ignore()并告诉会发生什么.
也可以在输入数字后检查是否使用cin.clear()和cin.sync().

use cin.ignore() before cin.getline() and tell what happens .
also you can check if using, cin.clear() and cin.sync() after the number is entered helps.


检查是否使用cin.clear()和cin.sync( ),输入号码后会有帮助.
check if using, cin.clear() and cin.sync() after the number is entered helps.


这篇关于为什么getline函数在if语句中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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