Methods for inputting strings in C: cin: Read strings from the console. getline(cin, string): Read a line of string until a newline character is encountered. stringstream: Process strings as streams, which can read and write data. ifstream: Read a string from a file.
Several ways to input strings in C
In C, there are the following ways to input strings Method:
1. cin
cin
is a standard input stream object in C. It can read a string from the console and store it in a variable. Usage example:
#include using namespace std; int main() { string input; cout << "Enter a string: "; cin >> input; cout << "You entered: " << input << endl; return 0; }
2. getline(cin, string)
getline(cin, string)
function is used to read from the console A line of string until a newline character is encountered. Usage example:
#include using namespace std; int main() { string input; cout << "Enter a string with spaces: "; getline(cin, input); cout << "You entered: " << input << endl; return 0; }
3. stringstream
stringstream
Allows strings to be processed as streams. It can read and write data from strings. Usage example:
#include using namespace std; int main() { string input = "Hello World!"; stringstream ss(input); string word; while (ss >> word) { cout << word << " "; } return 0; }
4. ifstream
##ifstreamis used to read data from a file. It can read a string from a file and store it in a variable. Usage example:
#include using namespace std; int main() { ifstream file("input.txt"); string input; while (getline(file, input)) { cout << input << endl; } file.close(); return 0; }
The above is the detailed content of Several methods of inputting strings in C++. For more information, please follow other related articles on the PHP Chinese website!