Home > Backend Development > C++ > body text

Several methods of inputting strings in C++

下次还敢
Release: 2024-05-01 15:36:18
Original
849 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

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:

<code class="cpp">#include <iostream>
using namespace std;

int main() {
  string input;
  cout << "Enter a string: ";
  cin >> input;
  cout << "You entered: " << input << endl;
  return 0;
}</code>
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:

<code class="cpp">#include <iostream>
using namespace std;

int main() {
  string input;
  cout << "Enter a string with spaces: ";
  getline(cin, input);
  cout << "You entered: " << input << endl;
  return 0;
}</code>
Copy after login

3. stringstream

stringstream Allows strings to be processed as streams. It can read and write data from strings. Usage example:

<code class="cpp">#include <sstream>
using namespace std;

int main() {
  string input = "Hello World!";
  stringstream ss(input);
  string word;
  while (ss >> word) {
    cout << word << " ";
  }
  return 0;
}</code>
Copy after login

4. ifstream

##ifstream is used to read data from a file. It can read a string from a file and store it in a variable. Usage example:

<code class="cpp">#include <fstream>
using namespace std;

int main() {
  ifstream file("input.txt");
  string input;
  while (getline(file, input)) {
    cout << input << endl;
  }
  file.close();
  return 0;
}</code>
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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template