首頁  >  文章  >  後端開發  >  c++中輸入字串的幾種方法

c++中輸入字串的幾種方法

下次还敢
下次还敢原創
2024-05-01 15:36:18804瀏覽

C 中輸入字串的方法:cin:從控制台讀取字串。 getline(cin, string):讀取一行字串,直到遇到換行符號。 stringstream:將字串當作流處理,可以讀取和寫入資料。 ifstream:從檔案中讀取字串。

c++中輸入字串的幾種方法

C 中輸入字串的幾種方法

在C 中,輸入字串有以下幾種方法:

1. cin

cin 是C 中標準的輸入流物件。它可以從控制台讀取字串,並將其儲存在變數中。用法範例:

<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>

2. getline(cin, string)

getline(cin, string) 函數用於從控制台讀取一行字串,直到遇到換行符。用法範例:

<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>

3. stringstream

#stringstream 允許字串作為流來處理。它可以從字串中讀取和寫入資料。用法範例:

<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>

4. ifstream

ifstream 用於從檔案中讀取資料。它可以從檔案中讀取字串,並將其儲存在變數中。用法範例:

<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>

以上是c++中輸入字串的幾種方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn