user198470
user198470

Reputation: 351

Count white spaces to the left of a line in a text file using C++

I am just trying to count the number of white spaces to the LEFT of a line from a text file. I have been using

count( line.begin(), line.end(), ' ' );

but obviously that includes ALL white spaces to the left, in between words and to the right. So basically what I'm wanting it to do is once it hits a non-space character stop it from counting the white spaces.

Thanks everyone.

Upvotes: 1

Views: 2361

Answers (5)

Nick Meyer
Nick Meyer

Reputation: 40272

Assuming line is a std::string, how about:

#include <algorithm>
#include <cctype>
#include <functional>

std::string::const_iterator firstNonSpace = std::find_if(line.begin(), line.end(),
   std::not1(std::ptr_fun<int,int>(isspace)));
int count = std::distance(line.begin(), firstNonSpace);

Upvotes: 9

Beta
Beta

Reputation: 99094

How about

line.find_first_not_of(' ');

EDIT: In case it's all spaces:

unsigned int n = line.find_first_not_of(' ');
if(n==s.npos)
    n = line.length();

Upvotes: 6

Loki Astari
Loki Astari

Reputation: 264411

Find the first non white space character.

std::string            test = "     plop";
std::string::size_type find = test.find_first_not_of(" \t");  // Note: std::string::npos returned when all space.

Technically not white space (as other characters are also white space).
Are you trying to count or strip white space?

If you are trying to strip white space then the stream operators do it automatically.

std::stringstream testStream(test);
std::string       word;

testStream >> word;  // white space stripped and first word loaded into 'word'

Upvotes: 6

JoeG
JoeG

Reputation: 13192

Is line a string?

In that case you want to std::string::find_first_not_of to find the first non-whitespace, then use std::count on the remainder of the line like this:

std::string::size_type firstNonSpace = line.find_first_not_of(' ');
std::size_t result = std::count(line.begin()+(firstNonSpace==std::string::npos?0:firstNonSpace),line.end(),' ');

Upvotes: 0

pajton
pajton

Reputation: 16226

int i = 0;
while ( isspace( line[i++] ) )
    ;
int whitespaceCnt = i-1;

Upvotes: 2

Related Questions