logo

C++ getline()

Cin — це об’єкт, який використовується для введення даних від користувача, але не дозволяє вводити дані в кількох рядках. Щоб прийняти кілька рядків, ми використовуємо функцію getline(). Це попередньо визначена функція, визначена в a файл заголовка, який використовується для прийому рядка або рядка з вхідного потоку, доки не зустрінеться символ розмежування.

Синтаксис функції getline():

Існує два способи представлення функції:

  • Перший спосіб оголошення полягає в передачі трьох параметрів.
 istream& getline( istream& is, string& str, char delim ); 

Наведений вище синтаксис містить три параметри, тобто є, вул , і я ділюсь .

Де,

це: Це об’єкт класу istream, який визначає, звідки читати вхідний потік.

str: Це рядковий об’єкт, у якому зберігається рядок.

число java в рядок
поділитися: Це розмежувальний символ.

Повернене значення

Ця функція повертає об’єкт вхідного потоку, який передається функції як параметр.

  • Другий спосіб оголошення полягає в передачі двох параметрів.
 istream& getline( istream& is, string& str ); 

Наведений вище синтаксис містить два параметри, тобто є і вул . Цей синтаксис майже схожий на наведений вище синтаксис; єдина відмінність полягає в тому, що він не має розмежувального характеру.

Де,

перетворити рядок на дату

це: Це об’єкт класу istream, який визначає, звідки читати вхідний потік.

str: Це рядковий об’єкт, у якому зберігається рядок.

Повернене значення

Ця функція також повертає вхідний потік, який передається функції як параметр.

Розберемося на прикладі.

По-перше, ми розглянемо приклад, у якому ми приймаємо введення користувача без використання функції 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>

У наведеному вище виводі ми дали ім’я «Джон Міллер» як введення користувача, але відображалося лише «Джон». Отже, ми робимо висновок, що cin не враховує символ, коли зустрічається пробіл.

Давайте розв’яжемо цю проблему за допомогою функції 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>

У наведеному вище виводі ми можемо помітити, що відображаються обидва слова, тобто Джон і Міллер, що означає, що функція getline() також враховує символ після пробілу.

Якщо ми не хочемо читати символ після пробілу, ми використовуємо такий код:

centos проти redhat
 #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>

Масив символів Getline

Ми також можемо визначити функцію getline() для масиву символів, але її синтаксис відрізняється від попереднього.

Синтаксис

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

У наведеному вище синтаксисі є два параметри; один є char *, а інший є розмір .

Де,

char*: Це символьний покажчик, який вказує на масив.

розмір: Він діє як роздільник, який визначає розмір масиву, тобто введення не може перевищувати цей розмір.

Розберемося на прикладі.

 #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>