0

I simply want to print out a set of integers, that are written down one on each line in a text file. Since I am using Linux, I cannot seem to use convenient functions like getch() and getline()

Please read my code below and tell me what I need to change to see the integers in the text file

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    fstream fp;
    fp.open("/home/Documents/C/Codeblocks/test1.txt", ios::in);

    int c;
    if(!fp)
    {
        cout<<"Cannot open file\n";
        return 1;
    }
    while(fp)
    {
        fp.get(c);
        cout << c;
    }
    //while ((c = getline(fp) != EOF))
      //  printf("%d\n", c);
}
2
  • 3
    getline will work also on linux. It's standard C++. Just pass the right arguments to it. (Hint: getline does not return as you expected) Commented Jul 7, 2015 at 14:39
  • Well, not on Codeblocks at least... Commented Jul 8, 2015 at 4:11

2 Answers 2

2

Really nice way to read things from file is by using streams. By using them you can easily read numbers seperated with whitespaces (e.g. newline, spaces, etc.) simply by using >> operator. Please read the first answer in following article, it suits perfectly to your issue:

Read Numeric Data from a Text File in C++

What you could to do is

int c;
while (fp >> c)
{
    cout << c << " ";
}

Also, you don't necessarily have to split declaration and definition of fstream fp; variable in your case. Simply put

fstream myfile("/home/Documents/C/Codeblocks/test1.txt", ios::in);
Sign up to request clarification or add additional context in comments.

Comments

1

Change your code to

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

int main() {
    int c;
    ifstream fp("/home/Documents/C/Codeblocks/test1.txt");
    if (!fp.is_open()) {
        cerr << "Cannot open file" << endl;
        return 1;
    }
    while (fp >> c)
        cout << c << endl;
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.