Thread: Using a string to open a file..

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    27

    Using a string to open a file..

    Well let's say i have :

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    
    int main(){
    
    string filename;
    
    cout<<"Give the name of the file you want to write"<<endl;
    cin>>filename;
    
    ofstream filepointer(filename);
    
    return 0;
    }
    It doesn't work.. But how can i use the string to be the filename.. ?

  2. #2
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    use filename.c_str().
    STL Util a small headers-only library with various utility functions. Mainly for fun but feedback is welcome.

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    27
    great, another thing is from what i know you can declare variables anywhere you want in c++ but i get a compile error when i try ..

    e.g :

    Code:
    int main(){
    int choice=0;
    
    cout<<"Give a number from 1 to 3"<<endl;
    cin>>choice;
    
     switch(choice){
     case 1:
      break;
     case 2:
      break;
     case 3:
      string whatever;   //I get an error here
      cin>>whatever;
      cout<<"You wrote"<<whatever<<endl;
      break;
    
     }
    return 0;
    }
    but when i put it in separate brackets like
    Code:
    {
    string whatever;
    cin>>whatever;
    cout<<"You wrote"<<whatever<<endl;
    }
    it works !

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > string whatever; //I get an error here
    Well paste your error message.
    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.

  5. #5
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Since the whatever variable has scope throughout the switch statement (as you've written it), it could be possible that code could access the variable without the variable being declared/initialized due to the code responsible for doing such being skipped as follows:
    Code:
    int value = 2;
    switch( value )
    {
    case 1:
        int foo = 5;
        break;
    case 2:
        cout << foo << endl;
        break;
    default:
        break;
    }
    The variable foo in the above switch statement is declared within the scope of the switch statement but it is possible that (as demonstrated above) that the int foo = 5; line of code can be skipped which would mean that foo was uninitialized/undeclared at the time we reach the cout statement. I know your code doesn't do anything like that (at least the small bit you've decided to share with us) but the compiler probably isn't smart enough to know that and wants you to make sure you understand what could happen and ensure you do something that in no uncertain term keeps that possibility from ever being realized. You can do that in two ways:

    1) The first way you've already discovered is to create the variable in a seperate block of code within brackets {}. This works because now there is no possible way you could potentially use that whatever variable outside of that block.

    2) The second way to resolve this would be to declare the whatever variable outside of the switch statment so that any potential use of said variable within any of the case's occurs with that variable fully declared and in scope.
    Code:
    string whatever;
    switch(choice)
    {
    case 1:
        break;
    case 2:
        break;
    case 3:
        cin>>whatever;
        cout<<"You wrote"<<whatever<<endl;
        break;
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  6. #6
    Registered User
    Join Date
    Apr 2006
    Posts
    27
    I get this error without the brackets... I get it even if i declare the string outside the switch..

    Code:
    main.cpp: In function ‘int main(int, char**)’:
    main.cpp:370: error: jump to case label
    main.cpp:365: error:   crosses initialization of ‘std::ofstream outputf’
    main.cpp:378: error: jump to case label
    main.cpp:365: error:   crosses initialization of ‘std::ofstream outputf’
    main.cpp:383: error: jump to case label
    main.cpp:365: error:   crosses initialization of ‘std::ofstream outputf’
    make: *** [cplus] Error 1
    This is the part of the program i get the errors ..
    Code:
      case 5:     //LINE 360
    	string filename;
    	cout<<"\033[2J\033[1;1H";
    	cout<<"Give the name of the file you want the lists to be saved : ";
    	cin>>filename;
    	ofstream outputf(filename.c_str());   //LINE 365
    	fifolist.save_list(outputf);
    	lifolist.save_list(outputf);
    	orderlist.save_list(outputf);   
          break;
        case 6:          //LINE 370
          cout<<"\033[2J\033[1;1H";
          cout<<fifolist;
          cout<<lifolist;
          cout<<orderlist;
          cout<<"Press ENTER to continue..";
          while(cin.get()!='\n');
          break;
        case 7:                //LINE 378
          cout<<"\033[2J\033[1;1H";
          cout<<"Press ENTER to exit..";
          while(cin.get()!='\n'); //i need to add exit(-1) after this line
          break;
        default:                //LINE 383
          break;    //LINE 384
    Last edited by neoragexxx; 04-27-2006 at 09:38 AM.

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    If you use the second solution, you have to declare all your variables outside the switch, including outputf.

    I think the first solution is better, though. If you only need the variables to exist for a single case, you should limit their scope with the exrta brackets.

    A third solution is to create a separate function for each complicated case. Opening an ofstream is complicated enough IMO to warrant a separate function. Then you can just call the function from your case without extra brackets.

  8. #8
    Registered User
    Join Date
    Apr 2006
    Posts
    27
    you are right i had to put both ofstream and string declaration outside the switch statement to work...i guess the solution with the brackets is better but at least now i know what was wrong

    thanks guys

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM