C++ 将 ifstream 中的一行读入字符串变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6663131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
reading a line from ifstream into a string variable
提问by Suhail Gupta
In the following code :
在以下代码中:
#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 :
Output :
This
This
Since >> operator reads upto the first whitespace i get this output. How can i extract the line back into the string ?
由于 >> 运算符读取到第一个空格,我得到了这个输出。如何将行提取回字符串?
I know this form of istream& getline (char* s, streamsize n );
but i want to store it in a string variable.How can i do this ?
我知道这种形式,istream& getline (char* s, streamsize n );
但我想将它存储在一个字符串变量中。我怎样才能做到这一点 ?
回答by jonsca
Use the std::getline()
from <string>
.
使用std::getline()
来自<string>
.
istream & getline(istream & is,std::string& str)
So, for your case it would be:
因此,对于您的情况,它将是:
std::getline(read,x);