i have written the code and tried to compile, but it always say that the file can't be read, yet i have put the same name file in one directory with the c++ file.

need your help so can read the file on my mac..

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

int main ()
{
    char filename[50];
    ifstream balwin;
    cin.getline(filename, 50);
    balwin.open(filename);

    if(!balwin.is_open ()) {
        cout << "doesnt found" << endl;
        exit (EXIT_FAILURE);
    }

    char word[50];
    balwin >> word;
    while(balwin.good()) {
        cout << word << " ";
        balwin >> word;
    }
    return 0;
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

First use code tags.

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

int main ()
{
char filename[50];
ifstream balwin;
cin.getline(filename, 50);
balwin.open(filename);

if(!balwin.is_open ()) {
cout << "doesnt found" << endl;
exit (EXIT_FAILURE);
}

char word[50];
balwin >> word;
while(balwin.good()) {
cout << word << " ";
balwin >> word;
}
return 0;
}

Line 11. You cannot open a char. Ifstream can only open a file.Don´t use the same names in your code.

yet i have put the same name file in one directory with the c++ file.

balwin.open("filename.txt");

Edited 5 Years Ago by alexchen: n/a

Line 11. You cannot open a char. Ifstream can only open a file.Don´t use the same names in your code.

balwin.open("filename.txt");

Actually, that's fine. The ifstream::open() method requires a C-style string as an argument. A C-style string is a char*, which an array of char is so long as there is a NULL character ('\0') indicating the end of the string it's storing. A string literal, like you have demonstrated, is automatically converted to a char* in memory.

@OP:
The problem is probably the location of the file. Make sure that you put it in the same directory as the finished executable, not your source files.

Edited 5 Years Ago by Fbody: n/a

This article has been dead for over six months. Start a new discussion instead.