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() 将不起作用
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
