Home  >  Article  >  Backend Development  >  How to Read a Complete Line of User Input Using getline() in C ?

How to Read a Complete Line of User Input Using getline() in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 06:33:03618browse

How to Read a Complete Line of User Input Using getline() in C  ?

Reading a Complete Line with getline() for File Writing

In C , reading a complete line of user input can be challenging. This article addresses the issue of reading multiple words from a line using the "cin" function.

We have an existing code that prompts the user for a line of text and writes it to a file. However, the code currently reads only one word at a time. To resolve this, we need to use the "getline()" function instead of "cin".

The corrected code should look like this:

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>

using namespace std;

int main()
{
    char x;

    cout << "Would you like to write to a file?" << endl;
    cin >> x;
    if (x == 'y' || x == 'Y')
    {
        string response;  // Changed data type to string
        cout << "What would you like to write?" << endl;
        getline(cin, response);  // Using getline() now

        ofstream file;
        file.open("Characters.txt");
        file << strlen(response) << " Characters." << endl;
        file << endl;
        file << response;

        file.close();

        cout << "Done. \a" << endl;
    }
    else
    {
        cout << "K, Bye." << endl;
    }

    return 0;
}

The essential change here is the use of "getline(cin, response)" instead of "cin >> y". "getline()" reads a line of text, including spaces, making it suitable for our purpose.

The above is the detailed content of How to Read a Complete Line of User Input Using getline() in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn