C++中的getline()函数用于从输入流中读取字符串或行。 getline()函数不会忽略前导空格字符。因此,应特别注意在cin之后使用getline() ,因为cin会忽略空格字符并将其留在流中作为垃圾。
程序1:
下面是C++程序进行说明:
C++
// C++ program for the above problem
#include
using namespace std;
// Driver Code
int main()
{
int fav_no;
string name;
cout << "Type your favorite number: ";
// The cin statement uses the
// fav_no and leaves the \n
// in the stream as garbage
cin >> fav_no;
cout << "Type your name : ";
// getline() reads \n
// and finish reading
getline(cin, name);
// In output only fav_no
// will be displayed not
// name
cout << name
<< ", your favourite number is : "
<< fav_no;
return 0;
}
C++
// C++ program for the above solution
#include
using namespace std;
// Driver Code
int main()
{
int fav_no;
string name;
cout << "Type your favourite number: ";
cin >> fav_no;
cout << "Type your name: ";
// Usage of std::ws will extract
// all the whitespace character
getline(cin >> ws, name);
cout << name
<< ", your favourite number is : "
<< fav_no;
return 0;
}
输出:
解释:
解决上述问题的方法是使用cin之后提取所有空白字符的东西。 C++中的std :: ws做同样的事情。实际上,它与输入流上的“ >>”运算符使用。
程式2:
下面是C++程序,用于说明上述问题的解决方案:
C++
// C++ program for the above solution
#include
using namespace std;
// Driver Code
int main()
{
int fav_no;
string name;
cout << "Type your favourite number: ";
cin >> fav_no;
cout << "Type your name: ";
// Usage of std::ws will extract
// all the whitespace character
getline(cin >> ws, name);
cout << name
<< ", your favourite number is : "
<< fav_no;
return 0;
}
输出:
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。