将文本文件读入字符串。 C ++ ifstream [英] Read text file into string. C++ ifstream
问题描述
void docDB(){
int sdb = 0;
ifstream dacb("kitudacbiet.txt");
if(!dacb.is_open())
cout<<"Deo doc dc file"<<endl;
else{
while(!dacb.eof()){
dacb>>dbiet[sdb].kitu;
dacb>>dbiet[sdb].mota;
//getline(dacb,dbiet[sdb].mota);
/*
string a="";
while((dacb>>a)!= '\n'){
//strcat(dbiet[sdb].mota,a);
dbiet[sdb].mota+=a;
}
*/
sdb++;
}
}
}
文本文件:kitudacbiet.txt
Text file: "kitudacbiet.txt"
\ Dau xuyet phai
@ Dau @
# Dau #
$ Ky hieu $
( Dau mo ngoac
) Dau dong ngoac
我想读取firt字串line into dbiet [sdb] .kitu,其余行放入dbiet [sdb] .mota
I want read firt string of line into dbiet[sdb].kitu and the rest of line into dbiet[sdb].mota
示例:line 1 = \ Dau xuyet phai
Example: line 1 = \ Dau xuyet phai
dbiet [sdb] .kitu =\和dbiet [sdb] .mota =Dau xuyet phai
dbiet[sdb].kitu = "\" and dbiet[sdb].mota = "Dau xuyet phai"
想要逐行读取,直到我遇到下行字符('\\\
')。如何做到这一点。
对不起我的英语不好.Thank
I would like to read line by line until i met downline character ('\n'). How to do this. Sorry my english not good.Thank
推荐答案
要从文件读取整行到字符串, code> std :: getline 像这样:
To read a whole line from a file into a string, use std::getline
like so:
std::ifstream file("my_file");
std::string temp;
std::getline(file, temp);
您可以在循环中执行此操作,直到文件结尾为止:
You can do this in a loop to until the end of the file like so:
std::ifstream file("my_file");
std::string temp;
while(std::getline(file, temp)) {
//Do with temp
}
参考资料
http://en.cppreference.com/w/cpp/string/basic_string/getline
http://en.cppreference.com/w/cpp/string/basic_string
这篇关于将文本文件读入字符串。 C ++ ifstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!