如何在getline之后获取输入
How to take input after getline
#include <iostream>
#include <string>
using namespace std;
struct Student
{
int ID;
long phno;
string name;
string depart;
string email;
};
int main ()
{
Student S1 ;
cout << "n=======================================================n" ;
cout << "Enter ID no. of student 1 : " ; cin >> S1.ID ;
cout << "Enter name of student 1 : " ; getline(cin, S1.name) ; cin.ignore();
cout << "Enter department of student 1 : " ; getline(cin, S1.depart) ; cin.ignore();
cout << "Enter email adress of student 1 : " ; getline(cin, S1.email) ; cin.ignore();
cout << "Enter phone number of student 1 : " ; cin >> S1.phno ;
return 0;
}
问题是它没有在email地址之后接受输入,程序忽略了在phno中接受输入,直接在email地址之后退出。
我对你的代码做了一些轻微的修改。
注意,当我在变量(cin >> S1.ID
或cin >> S1.phno
)上直接使用cin
后,我仅调用cin.ignore()
。
这是因为当你在int上使用cin
时,它会将n
留在缓冲区中。当你稍后调用getline(cin,...)
时,你只需要吸收剩下的n
,这被认为是你的整个"行"。"
这里有一个工作示例。
#include <iostream>
#include <string>
using namespace std;
struct Student
{
int ID;
long phno;
string name;
string depart;
string email;
};
int main ()
{
Student S1 ;
cout << "n=======================================================n" ;
cout << "Enter ID no. of student 1 :n" ;
cin >> S1.ID ;
cin.ignore();
cout << "Enter name of student 1 :n" ;
getline(cin, S1.name) ;
cout << "Enter department of student 1 :n" ;
getline(cin, S1.depart) ;
cout << "Enter phone number of student 1 :n" ;
cin >> S1.phno ;
cin.ignore();
cout << "Enter email adress of student 1 :n" ;
getline(cin, S1.email) ;
cout << endl << endl;
cout << S1.ID << endl << S1.name << endl << S1.depart << endl << S1.phno << endl << S1.email << endl;
return 0;
}
相关文章:
- 如何从用户那里获取输入并将其存储在向量中?
- 代码在执行之前终止,并且没有从用户那里获取输入
- 从用户获取输入/输出
- TFLite 隔离错误,通过获取C++输入和输出
- 如何使 std::istream 从键盘获取输入(如 std::cin)?
- 使用 qt 或 c++ 从桌面获取输入和输出
- 您如何在C++中不断获取输入?
- 从源代码本身C++获取输入
- 函数,从问题中获取输入,并在主函数中使用该输入
- 当我们声明 cin 为 int 并从 cin 中获取输入并在 cout 中打印 cin 时会发生什么?
- 如何在 std::map 中从 std::vector of std::p air 中获取输入?
- 有没有办法将 getline() 与外部文本文件一起使用,然后重新获得 cin 的控制权以从控制台获取输入?
- 从用户获取输入
- 我需要编写一个代码,从用户那里获取输入(句子)并停止在@处
- C 程序在获取输入[控制台应用程序]时跳过行
- 我在C++从函数中的用户获取输入、添加到数组和打印该数组时遇到问题
- 从用户那里获取输入,直到他输入一个数字
- 如何使用数组获取输入,并将其存储在record.h类的主类中的变量中
- getline 语句未获取输入
- 用户定义的功能用于竞争编程中,以获取输入