problem with c++ file I/O on xcode

Discussion in 'Mac Programming' started by mark5907, Jan 24, 2010.

  1. mark5907 macrumors newbie

    Joined:
    Jan 24, 2010
    #1
    I just start learning c++ programming and I am using xcode on my mac.


    I have a question about file I/O(maybe a very silly one)
    I tried to open Scopy.cpp and copy the content to another file Scopy2.cpp.
    I put both of the file in the directory same as the project.
    #include <string>
    #include <fstream>
    using namespace std;

    int main() {
    ifstream in("Scopy.cpp"); // Open for reading
    ofstream out("Scopy2.cpp"); // Open for writing
    string s;
    while(getline(in, s)) // Discards newline char
    out << s << "\n"; // ... must add it back
    }


    but nothing happened after I run the code.


    Please tell me how to do it in the right way?
     
  2. KnightWRX macrumors Pentium

    KnightWRX

    Joined:
    Jan 28, 2009
    Location:
    Quebec, Canada
    #2
  3. mark5907 thread starter macrumors newbie

    Joined:
    Jan 24, 2010
    #3
    thank you for you help, but I think we are not on the same page.

    I copy the example from the book "thinking in c++ volume 1"

    I tried the website, and use the following example from it.

    #include <iostream>
    #include <fstream>
    using namespace std;

    int main () {

    ifstream ifs ( "test.txt" , ifstream::in );

    while (ifs.good())
    cout << (char) ifs.get();
    ifs.close();

    return 0;
    }


    I made a file test.txt and type some random words in it. I put it in the working directory. but this is what I got after I run the code


    Loading program into debugger…
    Program loaded.
    run
    [Switching to process 3551]
    Running…

    Debugger stopped.
    Program exited with status value:0.
     
  4. KnightWRX macrumors Pentium

    KnightWRX

    Joined:
    Jan 28, 2009
    Location:
    Quebec, Canada
    #4
    Works like a champ here :

    Code:
    $ cat test.cpp
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main () {
    
    ifstream ifs ( "test.txt" , ifstream::in );
    
    while (ifs.good())
    cout << (char) ifs.get();
    ifs.close();
    
    return 0;
    }
    $ cat test.txt
    allo
    allo
    allo
    allo
    $ g++ -o test test.cpp
    $ ./test
    allo
    allo
    allo
    allo
    
    Are you sure your program is finding the test.txt file ?
     
  5. LtRammstein macrumors 6502a

    LtRammstein

    Joined:
    Jun 20, 2006
    Location:
    Denver, CO
    #5
    Make sure your test text file is in the project directory. If your file isn't in it, then you'll run into issues unless you put in the exact path.
     

Share This Page