Reputation: 129
I'm trying to count the number of lines of a wchar_t string on my C program using 2 methods: 1st method using a loop through the buffer counting "\n", the 2nd one is using wcstok()
however I got only the 2nd method returning the correct lines number, the 1st one returns always 0: here is my full program code:
#include <stdio.h>
#include <string.h>
const wchar_t* ret2line_template = L"\n";
int get_lines_count1(wchar_t* w){
int count=0;
int i;
for(i=0;i<wcslen(w);i++)if((w[i]==ret2line_template[0]) && (w[i+1]==ret2line_template[1]))count++;
return count;
}
int get_lines_count2(wchar_t* w){
int count=0;
wcstok(w, ret2line_template);
do{count++;}while(wcstok(0, ret2line_template));
return count;
}
int main(){
const wchar_t* s = L"00\n11\n22\n33";
const wchar_t* w;
w = calloc(sizeof(wchar_t*), wcslen(s)+1);
wcscpy(w, s);
printf("lines count from get_lines_count1 = %d\n", get_lines_count1(w)); //this returns 0: incorrect value
printf("lines count from get_lines_count2 = %d\n", get_lines_count2(w)); //this returns 4: the correct value
getch();
}
so what's wrong with my get_lines_count1
function and its loop? how to fix that problem? please help.
Upvotes: 0
Views: 88
Reputation: 66194
You're only incrementing count
in the first function if you match on a newline followed by a null char.
This:
ret2line_template[1]
in your conditional expression is looking at the second wchar_t in this:
const wchar_t* ret2line_template = L"\n";
which is the zero terminator. None of the pairs of wchar_t's in your string match this, so the result is zero. Just look for a L'\n'
. If there are chars left after the last one, add one more "line" to your count (the last one that has no L'\n'
trailing.
Upvotes: 3