简体   繁体   中英

How to skip integers in C++ taken from a fstream txt file?

I need to create a function that uses a loop. This function will open a text file and then must be able to skip a variable number of leading random integers. The program must be able to handle any number of leading random integers.

Example if the opened file reads this on its first line:

100 120 92 82 38 49 102

and the SKIP_NUMBER variable is assigned 3 the number the function would grab is 82.

The function must continue to grab the integers every SKIP_NUMBER until it reaches the end of the file. These integers taken from the txt file are then placed into another text file.

Please help I'm really lost on how to create this loop! :D

Here is my function so far...

//Function skips variables and returns needed integer
int skipVariable (int SKIP_NUMBER)
{

return 0; //temporary return
}

These are my program variables:

// initialize function/variables

ifstream fin;
string IN_FILE_NAME, OUT_FILE_NAME;
int SKIP_NUMBER;

If I were you, I would approach this problem like this:

1. create ifstream object m_strm
2. open the file
3. whie (m_strm.good())
    (a.) use ifstream's getline() to read a line from the file
    (b.) use strtok() function to tokenize the string (for whitespaces)
    (c.) maintain a counter when you keep getting tokens
    (d.) Now you can skip whenever you like.
4. Done with file, so close the stream!

This smells strongly of homework, especially since a quick check showed similar postings on other forums.

I'm not giving you the answer, but a basic thought process would be something along the lines of...

  1. open file with fin
  2. check for fail
  3. while not at the end of file:
  4. read in the variable
  5. increment a skip counter
  6. if( counter > SKIP_NUMBER) - write out the read in value and reset counter.

There will be other possible ways of going about this, but this should be somewhat solid. You'll have to do the work yourself and I wasn't very specific about most of the pitfalls. Be thorough.

My suggestion of how I would approach this:

  1. Write a function to read all of the numbers from a file and store them in an array/vector/list/whatever.
  2. Write a function which traverses the data structure, selects every (N+1)th items, and writes them to a file.

There are many ways of solving the problem of course.

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