Question about cout

So I have a question just to see if it is possible. I assume it is.
I am using Visual Studio and this is a console application.

Below is just a portion of the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    ifstream InFileCurrent;
    InFileCurrent.open ( "Current.txt" );
    ifstream InFileResistance;
    InFileResistance.open("Resistance.txt ");

    int i = 0;

    double Current, Resistance;
    double Current_Number[10];
    double Resistance_Number[10];
    double Volts_Product[10];

    int Current_Index = 0;
   
    if ( InFileCurrent.fail ( ) )										
    {
        cout << "The 'Current.txt' file you are you looking for can not be found. Please check spelling!" << endl;

    }


Okay so on line 2 it says InFileCurrent.open ("Current.txt")
This will of course grab the file Current.txt from the folder.

My question is if there is a way to display whatever is inside the parenthesis w/o having to manually put it in the cout statement. This question also refers to the Resistance.txt file.

This is not homework by the way. Just curious!!

Thanks!!!
Sure.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <fstream>

int main(int argc, const char* argv[])
{
    std::string filename = "Current.txt";
    std::ifstream fs(filename);

    if (!fs)
    {
        std::cout << "Couldn't open " << filename << std::endl;
    }

    return 0;
}


Hope this helps.
Write a function and wrap all the opening file and error handling behaviour in it. The code gets significantly shorter and cleaner this way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ifstream openFile(string filename) 
{
    ifsream filestream;
    filestream.open(filename);
    if (fileasteam.fail())
    {
        cout << "The '" << filename << "' file you are you looking for "
          "can not be found. Please check spelling!" << endl;
    }
    return filestream;
}

int main()
{
    ifstream InFileResistance = openFile("Resistance.txt");
    ifstream InFileCurrent = openFile("Current.txt");
    // ... whatever follows
}
Last edited on
Topic archived. No new replies allowed.