![](/img/trans.png)
[英]Empty string when reading into a string from ifstream with noskipws
[英]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.