Thread: Trouble understanding file input and output.

  1. #1
    Registered User
    Join Date
    Nov 2013

    Trouble understanding file input and output.

    I am trying to write a function that takes a string input from a file and then stores the string in a vector.

    I think the problem lies in the algorithm to take the input and store it in the vector. I am not sure how that is supposed to be done.

    This is my code:

    #include <iostream>#include <fstream>
    #include <vector>
    using namespace std;
    void rdFile(vector<string> svec)
        string line;
        ifstream myFile;"Text.txt");
        while (getline(myFile, line))
    int main()
        vector<string> svec;
        for (auto p = svec.begin(); p != svec.end(); p++)
            cout << *p;
        return 0;
    Can you see what is wrong, or help me to achieve the goal of the program?
    Any help is appreciated!
    Last edited by Iceboxes; 03-04-2014 at 06:59 AM.
    "Derp, derp, derp" - Me

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    1. getline does not keep the \n character with the string (which is probably what you want, but you will need to keep that in mind during output)
    2. If you pass-by-value into a function, the function makes a copy of the argument, and the original is unchanged. If you want the original to change, you need to pass-by-reference.

  3. #3
    Registered User
    Join Date
    Nov 2013
    Omg, I KNEW that, but completely forgot .... Another derp moment on this forum... So embarrasing >,< thank you so much for pointing the error out though!! You are a nice person :-)

  4. #4
    Join Date
    Oct 2007
    Inside my computer
    Some general advice...

    >> ifstream myFile;
    You can use the constructor:
    ifstream myFile("Text.txt");

    Not needed. Files close automatically due to the RAII principle.

    >> for (auto p = svec.begin(); p != svec.end(); p++)
    >> cout << *p;
    Can be simplified to
    for (auto & elem : svec)
        std::cout << elem;
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 19
    Last Post: 04-19-2012, 10:09 PM
  2. Replies: 1
    Last Post: 04-19-2012, 02:29 PM
  3. Replies: 16
    Last Post: 09-25-2011, 12:37 AM
  4. Replies: 5
    Last Post: 04-25-2011, 01:12 PM
  5. trouble understanding the source file structure
    By Mario F. in forum C++ Programming
    Replies: 5
    Last Post: 05-26-2006, 06:46 PM