Kingfisher Phuoc
Kingfisher Phuoc

Reputation: 8190

Find back slash (\) in C++

I have a problem with count number of back slash \ in C++, I have this code:

string path = "a\b\c";
int level = 0;
int path_length = path.size();
for(int i = 0; i < path_length; i++){
if(path.at(i) == '\\'){
        level++;
    }
}
cout << level << endl;

However, the level is always 0! Can you explain why? And how to count the number of /?

Upvotes: 2

Views: 10627

Answers (2)

Sanish
Sanish

Reputation: 1719

Backslashes in your variable should be escaped.

string path = "a\\b\\c";

Also you can use count function in algorithms library to avoid looping each character in the string and check whether it is backslash.

#include <iostream>
#include <string>
#include <algorithm>   // for count()
using namespace std;

int main()
{
string path = "a\\b\\c";
int no_of_backslash = (int)count(path.begin(), path.end(), '\\');
cout << "no of backslash " << no_of_backslash << endl;
}

Upvotes: 9

Luchian Grigore
Luchian Grigore

Reputation: 258618

Your string is invalid not what you expect it to be - it should be string path = "a\\b\\c";

You even get warnings (or at least MSVS provides warnings):

warning C4129: 'c' : unrecognized character escape sequence

Upvotes: 11

Related Questions