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

前端 未结 6 1913
执念已碎
执念已碎 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:11

    1. In the loop you are assigning value rather than comparing value so

    i=((Main.size())-1) -> i=(-1) since Main.size()

    Main[i] will yield "Vector Subscript out of Range" coz i = -1.

    2. You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.

    0 讨论(0)
  • 2020-12-01 07:20

    Just a piece of advice. Instead of writing

    for (int i=0; i=((Main.size())-1); i++) {
       cout << Main[i] << '\n';
    }
    

    as suggested above, write a:

    for (vector<double>::iterator it=Main.begin(); it!=Main.end(); it++) {
       cout << *it << '\n';
    }
    

    to use iterators. If you have C++11 support, you can declare i as auto i=Main.begin() (just a handy shortcut though)

    This avoids the nasty one-position-out-of-bound error caused by leaving out a -1 unintentionally.

    0 讨论(0)
  • 2020-12-01 07:20
      //file name must be of the form filename.yourfileExtension
           std::vector<std::string> 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;
        }
    }
    
    0 讨论(0)
  • 2020-12-01 07:22

    Just to expand on juanchopanza's answer a bit...

    for (int i=0; i=((Main.size())-1); i++) {
        cout << Main[i] << '\n';
    }
    

    does this:

    1. Create i and set it to 0.
    2. Set i to Main.size() - 1. Since Main is empty, Main.size() is 0, and i gets set to -1.
    3. Main[-1] is an out-of-bounds access. Kaboom.
    0 讨论(0)
  • 2020-12-01 07:25
    #include <iostream>
    #include <fstream>
    #include <vector>
    using namespace std;
    
    int main()
    {
    fstream dataFile;
    string name , word , new_word;
    vector<string> test;
    char fileName[80];
    cout<<"Please enter the file name : ";
    cin >> fileName;
    dataFile.open(fileName);
    if(dataFile.fail())
    {
         cout<<"File can not open.\n";
         return 0;
    }
    cout<<"File opened.\n";
    cout<<"Please enter the word : ";
    cin>>word;
    cout<<"Please enter the new word : ";
    cin >> new_word;
    while (!dataFile.fail() && !dataFile.eof())
    {
          dataFile >> name;
          test.push_back(name);
    }
    dataFile.close();
    
    }
    
    0 讨论(0)
  • 2020-12-01 07:35

    Your loop is wrong:

    for (int i=0; i=((Main.size())-1); i++) {
    

    Try this:

    for (int i=0; i < Main.size(); i++) {
    

    Also, a more idiomatic way of reading numbers into a vector and writing them to stdout is something along these lines:

    #include <iostream>
    #include <iterator>
    #include <fstream>
    #include <vector>
    #include <algorithm> // for std::copy
    
    int main()
    {
      std::ifstream is("numbers.txt");
      std::istream_iterator<double> start(is), end;
      std::vector<double> numbers(start, end);
      std::cout << "Read " << numbers.size() << " numbers" << std::endl;
    
      // print the numbers to stdout
      std::cout << "numbers read in:\n";
      std::copy(numbers.begin(), numbers.end(), 
                std::ostream_iterator<double>(std::cout, " "));
      std::cout << std::endl;
    
    }
    

    although you should check the status of the ifstream for read errors.

    0 讨论(0)
提交回复
热议问题