将文件读入内存C ++:std :: strings是否有getline()

时间:2018-11-08 16:28:32

标签: c++ fileinputstream stringstream string-parsing stdstring

我被要求更新我的代码,该代码读取一个文本文件并解析它以获取特定的字符串。

我基本上不想每次都打开文本文件,而是想将文本文件读入内存,并在对象持续时间内保存它。

我想知道是否有与getline()类似的函数可以像用于std :: ifstream那样用于std :: string。

我意识到我可以使用while / for循环,但是我很好奇是否还有其他方法。这是我目前正在做的事情:

file.txt:(\ n代表换行符)

file.txt

我的代码:

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(),因为它使获取文件的下一行变得更加容易。

2 个答案:

答案 0 :(得分:1)

如果您已经将数据读取为字符串,则可以使用std::stringstream将其转换为与getline兼容的文件状对象。

std::stringstream ss;
ss.str(file_contents_str);
std::string line;
while (std::getline(ss, line))
    // ...

答案 1 :(得分:0)

与其抓住一条线,然后尝试从中提取一件事,不提取一件事,然后丢弃该行,而不是呢?

    EditText editText = new EditText(this);
    LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);

    TextInputLayout textInputLayout = new TextInputLayout(this);
    LinearLayout.LayoutParams textInputLayoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);

    textInputLayout.setLayoutParams(textInputLayoutParams);
    textInputLayout.addView(editText, editTextParams);
    textInputLayout.setHint("hint");

    setContentView(textInputLayout);
相关问题