How to read a file into vector in C++?

前端 未结 6 1924
执念已碎
执念已碎 2020-12-01 06:34

I need to read from a .data or .txt file containing a new float number on each line into a vector.

I have searched far and wi

6条回答
  •  时光说笑
    2020-12-01 07:20

      //file name must be of the form filename.yourfileExtension
           std::vector source;
    bool getFileContent(std::string & fileName)
    {
        if (fileName.substr(fileName.find_last_of(".") + 1) =="yourfileExtension")
        {
    
            // Open the File
            std::ifstream in(fileName.c_str());
    
            // Check if object is valid
            if (!in)
            {
                std::cerr << "Cannot open the File : " << fileName << std::endl;
                return false;
            }
            std::string str;
            // Read the next line from File untill it reaches the end.
            while (std::getline(in, str))
            {
                // Line contains string of length > 0 then save it in vector
                if (str.size() > 0)
                    source.push_back(str);
            }
            /*for (size_t i = 0; i < source.size(); i++)
        {
            lexer(source[i], i);
            cout << source[i] << endl;
        }
        */
            //Close The File
            in.close();
            return true;
        }
        else
        {
            std::cerr << ":VIP doe\'s not support this file type" << std::endl;
            std::cerr << "supported extensions is filename.yourfileExtension" << endl;
        }
    }
    

提交回复
热议问题