Several methods of inputting strings in C++

下次还敢
Release: 2024-05-01 15:36:18
Original
712 people have browsed it

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 methods of inputting strings in C++

Several ways to input strings in C

In C, there are the following ways to input strings Method:

1. cin

cinis 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; }
Copy after login

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; }
Copy after login

3. stringstream

stringstreamAllows 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; }
Copy after login

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; }
Copy after login

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!

Related labels:
c++
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!