Abanoub
Abanoub

Reputation: 3809

how to know it's a new line in a text

i wanna read all the lines from a text so am doing this

int main(){
    fstream fs("test.txt",fstream::in|fstream::ate);
    int length = fs.tellg();
    std::vector<char> buffer(length);
    fs.seekg(0, ios::beg);
    fs.read(buffer.data(), length);

    int newlen= 0;
    int ptrSeek = 0;

    while(buffer.data()[ptrSeek] != 0){
        ptrSeek++;
        newlen++;
        if(ptrSeek == buffer.size()) { break;}
    }

    std::vector<char> temp(newlen,0);
    memcpy(&temp[0],&buffer[ptrSeek-newlen],newlen);

}

test.txt:

this is a test
this is a test

so when it reads it, it reads it like this

[t] [h] [i] [s] [ ] [i] [s] [ ] [a] [ ] [t] [e] [s] [t] [ ] [t] [h] [i] [s] [ ] [i] [s] [ ] [a] [ ] [t] [e] [s] [t]

how can i know it start reading from the next line?

Upvotes: 0

Views: 122

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361322

You can check against \n to know if the character is a newline.

However, in your case, I would suggest you to high-level function, such as std::getline which reads a single line at a time, saves you much of the labor you're doing manually.

The idiomatic way to read line would be as:

int countNewline= 0;
std::ifstream fs("test.txt");
std::string line;
while(std::getline(fs, line))
{
      ++countNewline;
      //a single line is read and it is stored in the variable `line`
      //you can process further `line`
      //example
      size_t lengthOfLine = line.size();
      for(size_t i = 0 ; i < lengthOfLine ; ++i)
          std::cout << std::toupper(line[i]); //convert into uppercase, and print it
      std::endl;
}

Upvotes: 3

Related Questions