SirRupertIII
SirRupertIII

Reputation: 12596

In C++, after opening a .txt file with values, reading the file gives me ""

Here's my code.

ifstream readFile;
readFile.open("voltages.txt");

if (readFile.fail( ) )
{
    cout << "\nCould not open the file ... check to see if voltages.txt exists\n";
    system("pause");
    return;
}

string tempString = "";
//readFile.seekg(0, ios::beg);
int idx = 0;
if (readFile.is_open())
{
    while ( readFile.good() )
    {
        getline(readFile,tempString);
        cout << tempString << endl;
    }
    readFile.close();
}

If I move the voltages.txt to c:/, then it works fine, but I have it in the same folder as my .exe right now, and when I set a breakpoint at cout << tempString << endl; it shows up just as "". I'd like to keep it in the .exe if possible. As you can see I tried seeking to the beginning, with no luck. Please help this C++ noob! Thank you!

Upvotes: 2

Views: 135

Answers (1)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33854

It might be because you are trying to read a local file when the program requires a link to the file from C:/

You can test this by replacing voltages.txt with C:/pathToVoltages/voltages.txt

I would suggest passing the file to your executable by doing this:

int main(int argc, char argv[]){
    ifstream readFile;
    readFile.open(argv[2]);
    /*Rest of the code*/

This assumes the path to the file is given by the first argument you give to the program as in:

./program pathToFile/voltages.txt

Hope this helps

Upvotes: 2

Related Questions