C++教程-C++getline()

C++ getline()
cin是一个对象,用于从用户处获取输入,但不允许多行输入。为了接受多行输入,我们使用getline()函数。getline()函数是一个预定义函数,定义在<string.h>头文件中,用于从输入流中接受一行或一个字符串,直到遇到定界字符。
getline()函数的语法:
有两种表示函数的方式:
- 第一种声明方式是传递三个参数。
istream& getline( istream& is, string& str, char delim );
以上语法包含三个参数,即is、str和delim。
其中,
is:istream类的对象,定义从哪里读取输入流。
str:存储字符串的string对象。
delim:定界字符。
返回值
该函数返回作为参数传递给函数的输入流对象。
- 第二种声明方式是传递两个参数。
istream& getline( istream& is, string& str );
以上语法包含两个参数,即is和str。该语法与上述语法几乎相同,唯一的区别是它没有定界字符。
其中,
is:istream类的对象,定义从哪里读取输入流。
str:存储字符串的string对象。
返回值
该函数也返回作为参数传递给函数的输入流对象。
让我们通过一个示例来理解。
首先,我们将看一个例子,其中我们不使用getline()函数来获取用户输入。
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
string name; // 变量声明
std::cout << "Enter your name :" << std::endl;
cin>>name;
cout<<"\nHello "<<name;
return 0;
}
在上面的代码中,我们使用cin>>name语句获取用户输入,即我们没有使用getline()函数。
输出
Enter your name : John Miller Hello John
在上面的输出中,我们将名字“John Miller”作为用户输入,但只显示了“John”。因此,我们得出结论,cin在遇到空格字符时不考虑后面的字符。
让我们通过使用getline()函数来解决上述问题。
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
string name; // 变量声明
std::cout << "Enter your name :" << std::endl;
getline(cin,name); // 使用getline()函数
cout<<"\nHello "<<name;
return 0;}
在上面的代码中,我们使用getline()函数来接受字符,即使遇到空格字符也能接受。
输出
Enter your name : John Miller Hello John Miller
在上面的输出中,我们可以观察到两个单词“John”和“Miller”,这意味着getline()函数也考虑了空格字符后的字符。
当我们不希望读取空格后的字符时,我们使用以下代码:
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
string profile; // 变量声明
std::cout << "Enter your profile :" << std::endl;
getline(cin,profile,' '); // 使用带有定界字符的getline()函数。
cout<<"\nProfile is :"<<profile;
}
在上面的代码中,我们使用getline()函数来接受字符,但这次我们还在第三个参数中添加了定界字符('')。这里的定界字符是空格字符,意味着在空格字符后出现的字符不会被考虑。
输出
Enter your profile : Software Developer Profile is: Software
获取getline()字符数组 我们还可以为字符数组定义getline()函数,但它的语法与前面的语法不同。
语法
istream& getline(char* , int size);
在上述语法中,有两个参数,一个是char*,另一个是size。
其中,
char*:它是指向数组的字符指针。
size:它充当分隔符,定义了数组的大小,意味着输入不能超过此大小。
让我们通过一个示例来理解。
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
char fruits[50]; // 数组声明
cout<< "Enter your favorite fruit: ";
cin.getline(fruits, 50); // 使用getline()函数
std::cout << "\nYour favorite fruit is :"<<fruits << std::endl;
return 0;
}
输出
Enter your favorite fruit: Watermelon
Your favorite fruit is: Watermelon