【发布时间】:2019-04-12 05:08:35
【问题描述】:
我被要求更新读取文本文件并将其解析为特定字符串的代码。
基本上不是每次都打开文本文件,而是想将文本文件读入内存并在对象的持续时间内拥有它。
我想知道是否有与 getline() 类似的函数可以用于 std::string,就像我可以用于 std::ifstream 一样。
我意识到我可以只使用 while/for 循环,但我很好奇是否还有其他方法。这是我目前正在做的事情:
file.txt: (\n 代表换行符)
我的代码:
ifstream file("/tmp/file.txt");
int argIndex = 0;
std::string arg,line,substring,whatIneed1,whatIneed2;
if(file)
{
while(std::getline(file,line))
{
if(line.find("3421",0) != string::npos)
{
std::getline(file,line);
std::getline(file,line);
std::stringstream ss1(line);
std::getline(file,line);
std::stringstream ss2(line);
while( ss1 >> arg)
{
if( argIndex==0)
{
whatIneed1 = arg;
}
argIndex++;
}
argIndex=0;
while( ss2 >> arg)
{
if( argIndex==0)
{
whatIneed2 = arg;
}
argIndex++;
}
argIndex=0;
}
}
}
whatIneed1=="whatIneed1" 和 whatIneed2=="whatIneed2" 到底在哪里。
有没有办法使用 getline() 之类的函数将 file.txt 存储在 std::string 而不是 std::ifstream asnd 中?我喜欢 getline(),因为它使获取文件的下一行变得容易得多。
【问题讨论】:
-
搜索“啜饮”
-
没有。
std::string对文件一无所知。在 C++ 中读取文件的唯一方法是使用文件流之一。请注意,有一些方法可以从 C++ 之外的文件中读取,但这些方法不太可能支持std::string。也不清楚你的最终目标是什么。
标签: c++ fileinputstream stringstream string-parsing stdstring