簡體   English   中英

將 ifstream 中的一行讀入字符串變量

[英]reading a line from ifstream into a string variable

在以下代碼中:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    string x = "This is C++.";
    ofstream of("d:/tester.txt");
    of << x;
    of.close();


    ifstream read("d:/tester.txt");
    read >> x;
    cout << x << endl ;
}

Output:

This

由於 >> 運算符讀取到第一個空格,我得到了這個 output。 如何將行提取回字符串中?

我知道這種形式的istream& getline (char* s, streamsize n ); 但我想將它存儲在一個字符串變量中。 我怎樣才能做到這一點?

使用來自<string>std::getline()

 istream & getline(istream & is,std::string& str)

因此,對於您的情況,它將是:

std::getline(read,x);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM