1

I am trying to make an integer vector by extracting integers from the text file. In the file, there are 10 numbers separated by a comma.

1,2,3,4,5,6,7,8,9,10

Like this.And my code is below

int main()
{
    ifstream read;
    read.open("input.txt");
    vector<int> arr;

    if (read)
    {
        int value;
        while (read >> value)
        {
            arr.push_back(value);
        }
    }
    read.close();
    return 0;
}

It compiles at least, but I don't know why it shows just wrong results

paddy
  • 60,864
  • 6
  • 61
  • 103
CodingPep
  • 51
  • 4

1 Answers1

1

Here is a simple example for doing the work

#include<fstream>
#include<vector>

int main() {

    std::ifstream read("input.txt");
    std::vector<int> arr;
    
    if(read) {
        int value;
        while(read >> vlaue) {
            arr.push_back(value); 
            read.get(); //ignore the separator character
        }
    }    
    read.close();
}

That's your program

  • Can I do that without .open()? – CodingPep Apr 13 '21 at 02:14
  • yes, it's the same thing, if you eventually needed to change the file you would just close it using `read.close()` and open it again with `read.open("other_input.txt")` – gallo magico Apr 13 '21 at 02:25
  • `read.seekg(0);` is pointless. When you open a `ifstream` in default mode the cursor is always at the beginning. Check your spelling -- `read >> vlaue` is a typo. Please avoid cluttering lines of code with comments saying what the line does. It makes code less readable and harder to follow. The only line of code worthy of comment is the `read.get()` but that comment should be more explicit about _why_ the next character is ignored. – paddy Apr 13 '21 at 03:18
  • How does the read.get() work here tho? – CodingPep Apr 13 '21 at 03:31
  • read.get() returns an int corresponding to the ascii value of the characters next to the stream cursor and moves the cursor by one position, in our case we just use it to move forward the cursor by one position, we need it for sipping the commas – gallo magico Apr 13 '21 at 03:43
  • 1. If the input has white spaces (this is how we usually input data) , it won’t work anymore since 'get' reads one character. 2. You do not check what you get: '1$3$` is also valid. 3. You do not check the file was successfully opened. 4. You do not need to explicitly close the file for it is automatically closed by the destructor. 5. 'read' is a poor choice for a stream identifier. – zdf Apr 13 '21 at 06:20