Manal
Manal

Reputation: 43

How to know it's the end of the line in c++ reading file

I need to know how to stop if it's the end of the line

this example of my file

I need the int value for the last element which is 15 and also for the other lines, I need to know if this value is the last element in the line

i try getline(file ,line) but it just gives me a string! and also line.length(); gives me the length of the file.

Upvotes: 0

Views: 1611

Answers (4)

O'Neil
O'Neil

Reputation: 3849

std::ifstream file{"your-file"};
std::string line;
while (getline(file, line)) {
    std::istringstream iss{line};
    std::vector<int> vec{std::istream_iterator<int>{iss},
                         std::istream_iterator<int>{}};
    if (vec.size() == 1) {
        // only one element
    }
    vec.back() // last value of the line (/!\ check not empty first)
}

Upvotes: 0

n.caillou
n.caillou

Reputation: 1342

This will extract the last number on each line:

ifstream f ("./numbers");
vector<int> v;
int i;
while (f >> i) {
    char c = f.get();
    if (f.eof() || c == '\r' || c == '\n') {
        v.push_back(i);
    }    
}

f.eof() may be true if the file is not terminated by a new line, in which case the f.get() call may fail and set the eofbit.

Upvotes: 1

NastyDiaper
NastyDiaper

Reputation: 2558

You should continue to use your getline function, from that you will have your std::string then to pull your last digit use:

string str = <getline() result>
size_t last_index = str.find_last_not_of("0123456789");
string result = str.substr(last_index + 1);
int num = std::stoi(result);

This will give you your int representation of your last number.

Upvotes: 2

Qrchack
Qrchack

Reputation: 947

You should either use std::getline and parse the string you get, or go char-by-char and treat CR/LF as end of line. Then just move back from it until you get a space.

Upvotes: 2

Related Questions