将文本文件读入字符串。C++ ifstream
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13551911/
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
Read text file into string. C++ ifstream
提问by bulubuloa
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++;
}
}
}
Text file: "kitudacbiet.txt"
文本文件:“kitudacbiet.txt”
\ Dau xuyet phai
@ Dau @
# Dau #
$ Ky hieu $
( Dau mo ngoac
) Dau dong ngoac
I want read firt string of line into dbiet[sdb].kitu and the rest of line into dbiet[sdb].mota
我想将第一行的字符串读入 dbiet[sdb].kitu 并将行的其余部分读入 dbiet[sdb].mota
Example: line 1 = \ Dau xuyet phai
示例:第 1 行 = \ Dau xuyet phai
dbiet[sdb].kitu = "\" and dbiet[sdb].mota = "Dau xuyet phai"
dbiet[sdb].kitu = "\" 和 dbiet[sdb].mota = "Dau xuyet phai"
I would like to read line by line until i met downline character ('\n'). How to do this. Sorry my english not good.Thank
我想逐行阅读,直到遇到下线字符('\n')。这该怎么做。对不起,我的英语不好。谢谢
回答by 111111
To read a whole line from a file into a string, use std::getline
like so:
要将文件中的整行读入字符串,请使用std::getline
如下命令:
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
}
References
参考
http://en.cppreference.com/w/cpp/string/basic_string/getline
http://en.cppreference.com/w/cpp/string/basic_string/getline
回答by Benjamin Lindley
It looks like you are trying to parse each line. You've been shown by another answer how to use getline
in a loop to seperate each line. The other tool you are going to want is istringstream
, to seperate each token.
看起来您正在尝试解析每一行。另一个答案向您展示了如何getline
在循环中使用来分隔每一行。您将需要的另一个工具是istringstream
, 分离每个令牌。
std::string line;
while(std::getline(file, line))
{
std::istringstream iss(line);
std::string token;
while (iss >> token)
{
// do something with token
}
}
回答by Taimur Amjad
getline(fin, buffer, '\n')
where fin
is opened file(ifstream object) and buffer
is of string/char
type where you want to copy line.
getline(fin, buffer, '\n')
在哪里fin
打开文件(ifstream 对象)并且buffer
是string/char
您要复制行的类型。