代码跳过 getline 语句.我尝试了getline和cin都没有成功
Code skips the getline statement. I tried both getline and cin with no success
我阅读了一些关于如何修复它的答案,但我也在尝试理解它背后的概念(即为什么第一条getline工作正常)。
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main(){
string ticker = "";
string date = "";
int pprice;
int sprice;
cout << "Enter the stock ticker =>" << endl;
getline(cin, ticker);
cout << "Enter the purchase price =>" << endl;
cin >> pprice;
它工作正常,直到它到达这里:
cout << "Enter the sell date =>" << endl;
getline(cin, date);
cout << "Enter the sell price =>" << endl;
cin >> sprice;
cout << ticker << endl;
return 0;
}
/*OUTPUT:
Enter the stock ticker =>
XYZ
Enter the purchase price =>
12.34
Enter the sell date =>
Enter the sell price =>
12.34
XYZ
*/
您可能没有在正确的位置使用cin.ignore()
。应在std::cin
之后和getline()
之前使用。
例如:
int x;
string y;
cin >> x;
cin.ignore(INT_MAX);
getline(cin, y);
这个想法是删除 cin 在流中留下的回车符、换行符等,这些回车符会导致 getline() 立即获取并返回。
相关文章:
- Getline(cin,str)的奇怪输出
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- C++ getline(cin,变量)行为不端.网站上没有任何解决方案有帮助
- 由于 getline(cin,s) 导致的 SIGABRT 错误
- 为什么我们需要在getline(cin,string)之前使用cin.ignore()
- 在C 中使用两个GetLine(CIN,S)
- 使用 getline(cin,n) 输入;没有打印第一个输入,我没有使用 CIN >> 在任何地方输入
- 为什么必须键入 getline(cin,字符串)两次
- 无法删除 txt 文件中 getline(cin , (变量)) 之后的下一行
- getline(cin,_string);
- 当使用getline(cin,string)时,CIN会自动获取其值而不询问
- 我的程序跳过getline(cin,CustInfo),进入CustomerInfo函数中的City.我该怎么修
- Using cin AFTER getline(cin, string)
- 如何正确使用"getline(cin, input);"
- 关于getline(cin,string)的C++快速问题
- getline(cin,s1)没有提示我输入
- 为什么 cin.ignore() 后面的 getline(cin, var) 不读取字符串的第一个字符?
- 为什么getline(cin,string_name)在我第一次在循环中使用它时会创建一个空字符串
- getline(cin,aString)接收输入而不输入另一个值
- getline(cin,string)与cin.ignore()一起不工作