简体   繁体   中英

Read Text File Line by Line, then word by word c++, push on to an array

My data looks like:

numbers.text

12     32     21     42

33     566    332    12

66     994    4      33

12     33     33     41

and I want to push the first three values on an vector of integers while ignoring the last value. Every line I need to have a new vector of the first 3 numbers in there. Just spaces are used as separators (a TAB). thanks!

Well, ultimately you want to end up with an std::vector<int> of 3 integers for each line in the text file. This is basically an exercise in parsing the file, which is very easy to do using a C++ file stream object along with a stream input iterator.

Use an std::ifstream object to open the file. You can then iterate over each integer in the file using an std::istream_iterator<int> . This will extract each integer, so you can store it in a vector. If you want to discard the fourth integer on each line, just keep a counter variable handy so that you can discard every 4th value.

And that's basically it. I'll leave it to you to actually produce the code.

  1. open the file
  2. iterate over each line in the file with std::getline()
  3. parse the integers out of the line and into a vector
    1. place the line in a std::istringstream to parse the integers out
    2. extract three integers from the string stream
    3. push the integers into a vector
    4. what do you want to do with the vector? maybe push that into another vector?

Notice what happened here: You wrote a question, I translated it into a sequence of instructions, and finally you translate that into code. That's how we write simple programs. The trick is in understanding the question well enough to translate it into pseudocode as above.

std::ifstream will work if you are just reading the file directly. If you are using getline (which really isn't necessary here), you can write a simple split function to separate the values and insert the ones you want. Since this sounds like schoolwork, I doubt you'll want to use the boost:: methods that would make this rather trivial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM