getline() skipping first even after clear()(getline() 即使在 clear() 之后也会先跳过)
问题描述
所以我有一个函数可以不断跳过第一个 getline 并直接跳到第二个 getline.我试图清除缓冲区但仍然没有运气,这是怎么回事?
So I have a function that keeps skipping over the first getline and straight to the second one. I tried to clear the buffer but still no luck, what's going on?
void getData(char* strA, char* strB)
{
    cout << "Enter String 1: ";               // Shows this line
    cin.clear();
    cin.getline(strA, 50);                    // 50 is the character limit, Skipping Input
    cout << endl << "Enter String 2: ";       // Showing This Line
    cin.clear();
    cin.getline(strB, 50);                   // Jumps Straight to this line
}
推荐答案
确保你没有使用 cin >>字符串.在调用函数之前.如果你使用 cin >>str 然后要使用getline(cin, str),必须先调用cin.ignore().
Make sure you didn't use cin >> str. before calling the function. If you use cin >> str and then want to use getline(cin, str), you must call cin.ignore() before.
string str;
cin >> str;
cin.ignore(); // ignores 
 that cin >> str has lefted (if user pressed enter key)
getline(cin, str);
如果使用 c 字符串:
In case of using c-strings:
char buff[50];
cin.get(buff, 50, ' ');
cin.ignore();
cin.getline(buff, 50);
添加:你的错误可能不在函数本身,而是在调用函数之前.cin 流必须在第一个 cin.getline 中仅读取换行符 
'.
ADD: Your wrong is not probably in the function itself, but rather before calling the function. The stream cin have to read only a new line character 
' in first cin.getline.
这篇关于getline() 即使在 clear() 之后也会先跳过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:getline() 即使在 clear() 之后也会先跳过
				
        
 
            
        基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				