getline() does not work if used after some inputs(如果在某些输入之后使用 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() 将不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果在某些输入之后使用 getline() 将不起作用


- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01
- 近似搜索的工作原理 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01