从ifstream读取一行到字符串变量 [英] reading a line from ifstream into a string variable
本文介绍了从ifstream读取一行到字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在以下代码中:
#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 ;
}
输出:
This
第一个空格我得到这个输出。我如何提取回行到字符串?
Since >> operator reads upto the first whitespace i get this output. How can i extract the line back into the string ?
我知道这种形式的 istream& getline(char * s,streamsize n);
但我想将它存储在字符串变量中。
我该如何做?
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 ?
推荐答案
使用 <$来自< string>
的c $ c> std :: getline() 。
Use the std::getline()
from <string>
.
istream & getline(istream & is,std::string& str)
be:
std::getline(read,x);
这篇关于从ifstream读取一行到字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文