如果在某些输入之后使用 getline() 将不起作用 [英] getline() does not work if used after some inputs

查看:15
本文介绍了如果在某些输入之后使用 getline() 将不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在getline()方面需要帮助

getline() 不起作用,如果我在一些输入后使用它,即

getline() is not working, if I use it after some inputs, i.e.

#include<iostream>
using namespace std;

main()
{
string date,time;
char journal[23];


cout<<"Date:	";
cin>>date;
cout<<"Time:	";
cin>>time;

cout<<"Journal Entry:	";
cin.getline(journal,23);


cout<<endl;
system("pause");
}

就好像我在输入之上使用 getline() 一样,它确实有效,即

where as if I use getline() on top of inputs, it does work i.e.

cout<<"Journal Entry:	";
cin.getline(journal,23);
cout<<"Date:	";
cin>>date;
cout<<"Time:	";
cin>>time;

可能是什么原因?

推荐答案

字符被提取,直到 (n - 1) 个字符被提取提取或找到分隔符(如果此为分隔符参数已指定,否则为 ' ').提取也停止如果在输入序列中到达文件末尾或出现错误在输入操作期间发生.

Characters are extracted until either (n - 1) characters have been extracted or the delimiting character is found (which is delimiter if this parameter is specified, or ' ' otherwise). The extraction also stops if the end of the file is reached in the input sequence or if an error occurs during the input operation.

cin.getline() 从输入中读取时,输入流中会留下一个换行符,因此它不会读取您的 c 字符串.在调用 getline() 之前使用 cin.ignore().

When cin.getline() reads from the input, there is a newline character left in the input stream, so it doesn't read your c-string. Use cin.ignore() before calling getline().

cout<<"Journal Entry:	";
cin.ignore();
cin.getline(journal,23);

这篇关于如果在某些输入之后使用 getline() 将不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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