Reading line from text file and putting the strings into a vector?

前端 未结 3 1590
终归单人心
终归单人心 2020-11-29 03:03

I am trying to read each line of a textfile which each line contains one word and put those words into a vector. How would i go about doing that?

This is my new code

3条回答
  •  独厮守ぢ
    2020-11-29 03:48

    Simplest form:

    std::string line;
    std::vector myLines;
    while (std::getline(myfile, line))
    {
       myLines.push_back(line);
    }
    

    No need for crazy c thingies :)

    Edit:

    #include 
    #include 
    #include 
    #include 
    
    int main()
    
    {
        std::string line;
        std::vector DataArray;
        std::vector QueryArray;
        std::ifstream myfile("OHenry.txt");
        std::ifstream qfile("queries.txt");
    
        if(!myfile) //Always test the file open.
        {
            std::cout<<"Error opening output file"<< std::endl;
            system("pause");
            return -1;
        }
        while (std::getline(myfile, line))
        {
            DataArray.push_back(line);
        }
    
        if(!qfile) //Always test the file open.
        {
            std::cout<<"Error opening output file"<

    Keyword using is illegal C++! Never use it. OK? Good. Now compare what I wrote with what you wrote and try to find out the differences. If you still have questions come back.

提交回复
热议问题