0

i m trying to read from a file and stop when i hit end of line. the thing is, it doesnt seem to work.¯_(ツ)_/¯ any ideas why?

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

int main(){
    char a;
    ifstream myfile;
    myfile.open("text.txt");
    while (!myfile.eof())
    {
    myfile>> a;
    if (a=='\n')
    cout << "end of line";

    }
myfile.close();
}

text file i read:

text file i read

Suraj Rao
  • 28,186
  • 10
  • 88
  • 94

4 Answers4

1

Try while (myfile.get(a)) instead?

while (myfile.get(a))
{
    if (a=='\n')
        cout << "end of line";

}
siamezzze
  • 81
  • 3
  • 5
  • @deW1 the example from the question was about character-by-character read, I assumed there is a reason for it. Sure, there is more than one way to do it, as shown in other answers. – siamezzze Apr 30 '17 at 12:49
1

Why make things harder than needed. If you want to parse lines, then use std::getline().

#include <iostream>
#include <fstream>

int main(int argc, char *argv[]) {
    std::ifstream myfile("text.txt");

    std::string line;
    while (std::getline(myfile, line)) {
        std::cout << "end of line" << std::endl;
    }
}
Jeffery Thomas
  • 40,388
  • 8
  • 88
  • 114
0

using a for loop

std::ifstream ifs( "file" );
for( char chr = 0; ifs.peek() != '\n'; ifs.get( chr ) ){
    std::cout << chr;
}
ifs.close();
Shakiba Moshiri
  • 13,741
  • 2
  • 20
  • 35
0

I just rewrite your code:

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

int main(){
    char a;
    ifstream myfile;
    myfile.open("/Users/sijan/CLionProjects/test2/text.txt",ifstream::in);
    while (myfile.get(a))
    {
        cout<< a;

        if (a=='\n')
            cout << "end of line\n";
    }

    if (myfile.eof())
        cout << "end of file";
    myfile.close();
}
Shohan Ahmed Sijan
  • 3,775
  • 1
  • 28
  • 37