logo

C++ getline()

O cin é um objeto usado para receber a entrada do usuário, mas não permite receber a entrada em várias linhas. Para aceitar as múltiplas linhas, usamos a função getline(). É uma função pré-definida definida em um arquivo de cabeçalho usado para aceitar uma linha ou string do fluxo de entrada até que o caractere delimitador seja encontrado.

Sintaxe da função getline():

Existem duas maneiras de representar uma função:

  • A primeira forma de declarar é passar três parâmetros.
 istream& getline( istream& is, string& str, char delim ); 

A sintaxe acima contém três parâmetros, ou seja, é, str , e eu compartilho .

Onde,

é: É um objeto da classe istream que define de onde ler o fluxo de entrada.

estr: É um objeto string no qual a string é armazenada.

comando de estiramento do autocad
compartilhar: É o caráter delimitador.

Valor de retorno

Esta função retorna o objeto de fluxo de entrada, que é passado como parâmetro para a função.

  • A segunda forma de declarar é passar dois parâmetros.
 istream& getline( istream& is, string& str ); 

A sintaxe acima contém dois parâmetros, ou seja, é e str . Esta sintaxe é quase semelhante à sintaxe acima; a única diferença é que não possui nenhum caráter delimitador.

Onde,

coleções em java

é: É um objeto da classe istream que define de onde ler o fluxo de entrada.

estr: É um objeto string no qual a string é armazenada.

Valor de retorno

Esta função também retorna o fluxo de entrada, que é passado como parâmetro para a função.

Vamos entender através de um exemplo.

Primeiro, veremos um exemplo onde pegamos a entrada do usuário sem usar a função getline().

 #include #include using namespace std; int main() { string name; // variable declaration std::cout &lt;&lt; &apos;Enter your name :&apos; &lt;&gt;name; cout&lt;<'
hello '<<name; return 0; } < pre> <p>In the above code, we take the user input by using the statement <strong>cin&gt;&gt;name,</strong> i.e., we have not used the <strong>getline()</strong> function.</p> <p> <strong>Output</strong> </p> <pre> Enter your name : John Miller Hello John </pre> <p>In the above output, we gave the name &apos;John Miller&apos; as user input, but only &apos;John&apos; was displayed. Therefore, we conclude that cin does not consider the character when the space character is encountered.</p> <p> <strong>Let&apos;s resolve the above problem by using getline() function.</strong> </p> <pre> #include #include using namespace std; int main() { string name; // variable declaration. std::cout &lt;&lt; &apos;Enter your name :&apos; &lt;&lt; std::endl; getline(cin,name); // implementing a getline() function cout&lt;<'
hello '<<name; return 0;} < pre> <p>In the above code, we have used the <strong>getline()</strong> function to accept the character even when the space character is encountered.</p> <p> <strong>Output</strong> </p> <pre> Enter your name : John Miller Hello John Miller </pre> <p>In the above output, we can observe that both the words, i.e., John and Miller, are displayed, which means that the getline() function considers the character after the space character also.</p> <p> <strong>When we do not want to read the character after space then we use the following code:</strong> </p> <pre> #include #include using namespace std; int main() { string profile; // variable declaration std::cout &lt;&lt; &apos;Enter your profile :&apos; &lt;&lt; std::endl; getline(cin,profile,&apos; &apos;); // implementing getline() function with a delimiting character. cout&lt;<'
profile is :'<<p>In the above code, we take the user input by using getline() function, but this time we also add the delimiting character(&apos;&apos;) in a third parameter. Here, delimiting character is a space character, means the character that appears after space will not be considered.<p></p> <p> <strong>Output</strong> </p> <pre> Enter your profile : Software Developer Profile is: Software </pre> <h3>Getline Character Array</h3> <p>We can also define the getline() function for character array, but its syntax is different from the previous one.</p> <p> <strong>Syntax</strong> </p> <pre> istream&amp; getline(char* , int size); </pre> <p>In the above syntax, there are two parameters; one is <strong>char</strong> *, and the other is <strong>size</strong> .</p> <p> <strong>Where,</strong> </p> <p> <strong>char*:</strong> It is a character pointer that points to the array.</p> <p> <strong>Size:</strong> It acts as a delimiter that defines the size of the array means input cannot cross this size.</p> <p> <strong>Let&apos;s understand through an example.</strong> </p> <pre> #include #include using namespace std; int main() { char fruits[50]; // array declaration cout&lt;&lt; &apos;Enter your favorite fruit: &apos;; cin.getline(fruits, 50); // implementing getline() function std::cout &lt;&lt; &apos;
Your favorite fruit is :&apos;&lt;<fruits << std::endl; return 0; } < pre> <p> <strong>Output</strong> </p> <pre> Enter your favorite fruit: Watermelon Your favorite fruit is: Watermelon </pre> <hr></fruits></pre></'
profile></pre></'
hello></pre></'
hello>

Na saída acima, demos o nome ‘John ​​Miller’ como entrada do usuário, mas apenas ‘John’ foi exibido. Portanto, concluímos que cin não considera o caractere quando o caractere de espaço é encontrado.

Vamos resolver o problema acima usando a função getline().

 #include #include using namespace std; int main() { string name; // variable declaration. std::cout &lt;&lt; &apos;Enter your name :&apos; &lt;&lt; std::endl; getline(cin,name); // implementing a getline() function cout&lt;<\'
hello \'<<name; return 0;} < pre> <p>In the above code, we have used the <strong>getline()</strong> function to accept the character even when the space character is encountered.</p> <p> <strong>Output</strong> </p> <pre> Enter your name : John Miller Hello John Miller </pre> <p>In the above output, we can observe that both the words, i.e., John and Miller, are displayed, which means that the getline() function considers the character after the space character also.</p> <p> <strong>When we do not want to read the character after space then we use the following code:</strong> </p> <pre> #include #include using namespace std; int main() { string profile; // variable declaration std::cout &lt;&lt; &apos;Enter your profile :&apos; &lt;&lt; std::endl; getline(cin,profile,&apos; &apos;); // implementing getline() function with a delimiting character. cout&lt;<\'
profile is :\'<<p>In the above code, we take the user input by using getline() function, but this time we also add the delimiting character(&apos;&apos;) in a third parameter. Here, delimiting character is a space character, means the character that appears after space will not be considered.<p></p> <p> <strong>Output</strong> </p> <pre> Enter your profile : Software Developer Profile is: Software </pre> <h3>Getline Character Array</h3> <p>We can also define the getline() function for character array, but its syntax is different from the previous one.</p> <p> <strong>Syntax</strong> </p> <pre> istream&amp; getline(char* , int size); </pre> <p>In the above syntax, there are two parameters; one is <strong>char</strong> *, and the other is <strong>size</strong> .</p> <p> <strong>Where,</strong> </p> <p> <strong>char*:</strong> It is a character pointer that points to the array.</p> <p> <strong>Size:</strong> It acts as a delimiter that defines the size of the array means input cannot cross this size.</p> <p> <strong>Let&apos;s understand through an example.</strong> </p> <pre> #include #include using namespace std; int main() { char fruits[50]; // array declaration cout&lt;&lt; &apos;Enter your favorite fruit: &apos;; cin.getline(fruits, 50); // implementing getline() function std::cout &lt;&lt; &apos;
Your favorite fruit is :&apos;&lt;<fruits << std::endl; return 0; } < pre> <p> <strong>Output</strong> </p> <pre> Enter your favorite fruit: Watermelon Your favorite fruit is: Watermelon </pre> <hr></fruits></pre></\'
profile></pre></\'
hello>

Na saída acima, podemos observar que ambas as palavras, ou seja, John e Miller, são exibidas, o que significa que a função getline() também considera o caractere após o caractere de espaço.

Quando não queremos ler o caractere após o espaço, usamos o seguinte código:

falha de proteção geral
 #include #include using namespace std; int main() { string profile; // variable declaration std::cout &lt;&lt; &apos;Enter your profile :&apos; &lt;&lt; std::endl; getline(cin,profile,&apos; &apos;); // implementing getline() function with a delimiting character. cout&lt;<\'
profile is :\'<<p>In the above code, we take the user input by using getline() function, but this time we also add the delimiting character(&apos;&apos;) in a third parameter. Here, delimiting character is a space character, means the character that appears after space will not be considered.<p></p> <p> <strong>Output</strong> </p> <pre> Enter your profile : Software Developer Profile is: Software </pre> <h3>Getline Character Array</h3> <p>We can also define the getline() function for character array, but its syntax is different from the previous one.</p> <p> <strong>Syntax</strong> </p> <pre> istream&amp; getline(char* , int size); </pre> <p>In the above syntax, there are two parameters; one is <strong>char</strong> *, and the other is <strong>size</strong> .</p> <p> <strong>Where,</strong> </p> <p> <strong>char*:</strong> It is a character pointer that points to the array.</p> <p> <strong>Size:</strong> It acts as a delimiter that defines the size of the array means input cannot cross this size.</p> <p> <strong>Let&apos;s understand through an example.</strong> </p> <pre> #include #include using namespace std; int main() { char fruits[50]; // array declaration cout&lt;&lt; &apos;Enter your favorite fruit: &apos;; cin.getline(fruits, 50); // implementing getline() function std::cout &lt;&lt; &apos;
Your favorite fruit is :&apos;&lt;<fruits << std::endl; return 0; } < pre> <p> <strong>Output</strong> </p> <pre> Enter your favorite fruit: Watermelon Your favorite fruit is: Watermelon </pre> <hr></fruits></pre></\'
profile>

Matriz de caracteres Getline

Também podemos definir a função getline() para array de caracteres, mas sua sintaxe é diferente da anterior.

Sintaxe

 istream&amp; getline(char* , int size); 

Na sintaxe acima, existem dois parâmetros; um é Caracteres *, e o outro é tamanho .

Onde,

Caracteres*: É um ponteiro de caractere que aponta para o array.

Tamanho: Ele atua como um delimitador que define o tamanho do array, significa que a entrada não pode ultrapassar esse tamanho.

Vamos entender através de um exemplo.

 #include #include using namespace std; int main() { char fruits[50]; // array declaration cout&lt;&lt; &apos;Enter your favorite fruit: &apos;; cin.getline(fruits, 50); // implementing getline() function std::cout &lt;&lt; &apos;
Your favorite fruit is :&apos;&lt;<fruits << std::endl; return 0; } < pre> <p> <strong>Output</strong> </p> <pre> Enter your favorite fruit: Watermelon Your favorite fruit is: Watermelon </pre> <hr></fruits>