Home > Article > Backend Development > How to Read a Complete Line of User Input Using getline() in C ?
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!