Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

find "\n" in simple string

Status
Not open for further replies.

hugh7

Technical User
Mar 2, 2003
24
US

I'm trying to find the number of newline characters in a simple string but keep getting 0 for the variable numline.
What can I do to find the two little newline commands?
Here is my code:
(as you can see I'm a beginner)
//stringstep

#include <iostream>

using namespace std;

int endline=0 ;
int numline=0 ;
int counter=0 ;

// this is my string sample
char harb2[ ]=&quot; Find the end&quot; &quot;\n&quot; &quot;Then you will see&quot; &quot;\n&quot; ;
int lsizharb=strlen(harb2) ;

int main( )
{

for (counter=0;counter<=lsizharb; counter++)
if(harb2[counter]==0) // this seems to get end of string marker
endline++;
if(harb2[counter]=='\n') // this ends up with 0 !
numline++;

cout <<numline << endl;

return 0;

}
 
WRONG>>>

for (counter=0;counter<=lsizharb; counter++)
if(harb2[counter]==0) // this seems to get end of string marker
endline++;
if(harb2[counter]=='\n') // this ends up with 0 !
numline++;

RIGHT>>>>>

for (counter=0;counter<=lsizharb; counter++)
{
if(harb2[counter]==0) // this seems to get end of string marker
endline++;
if(harb2[counter]=='\n') // this ends up with 0 !
numline++;
}
 
Or try:
Code:
#include <cstring>
int CountChars(const char* s, char ch = '\n')
{
  int count;
  for (count = 0; (s=strchr(s,ch)) != 0; ++s, ++count)
    ;
  return count;
}
 
Hi CD
..Ah the braces! Thanks for the help

Hugh
 
Hi ArkM,

I'll give your suggestion a try.
Thanks

Hugh
 
Heh? I don't understand your method. Personally, I would have used:
...
char harb2[ ]=&quot; Find the end&quot; &quot;\n&quot; &quot;Then you will see &quot;\n&quot;;
int nCount=0;
int harbLen=sizeof harb2 / sizeof harb2[0];

for(int i=0;i<harbLen && harb2[ i ] != 0;i++)
if(harb2[ i ] == '\n')
nCount++;
...
 
Hi Blazero,

Do you mean my 'method'?
I thought I would step through the string , character by character and find the line breaks. That's it.
Since I'm only a beginner with C++ this is all I could come up with.
I'll study your example. It certainly looks more compact.
I've been reading about the string library and have lots to think about and practice.
Thanks for your reply

Hugh
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top