如果在某些输入之后使用 getline() 将不起作用

2022-01-12 00:00:00 char c++ 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);

相关文章