Thread: Opening Text File

  1. #1
    Registered User
    Join Date
    May 2011

    Opening Text File

    I am reading a text file which has two columns of data. The following program works when is replaced simply with"001.txt"). Why does it not work when I declare afile beforehand? Although it may not seem important for this particular code, it is necessary for my future tasks. Thank you in advance.

    #include <iostream>
    #include <fstream>
    using namespace std;
    int main (){
    	string afile = "001.txt";
        	ifstream readfile;;
    	const int n = 10;
        	double x[n], y[n];
        	for (int i=0; i<n; i++)
    		cout<<x[i]<<" "<<y[i]<<endl;

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    segmentation fault
    First parameter to open is a C-string, not a std::string. Try:

    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    You need to say this

    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    May 2011
    Thanks a lot. Works perfectly.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Opening a text file
    By bwisdom in forum C++ Programming
    Replies: 6
    Last Post: 04-28-2008, 09:17 AM
  2. Opening and reading text files
    By pete212 in forum C Programming
    Replies: 3
    Last Post: 04-22-2008, 10:16 AM
  3. Opening text file
    By zdude in forum C Programming
    Replies: 3
    Last Post: 10-31-2002, 08:23 AM
  4. Opening a text file in C
    By lotus in forum C Programming
    Replies: 17
    Last Post: 05-27-2002, 12:30 PM
  5. trouble opening a text file
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 05-05-2002, 09:11 PM