ive been doing a intro to c++ in college.
i am required to count number of non blank charactersfrom a string. I know i have to subtract the number of spaces from total characters...BUT i cant count the number of spaces. anyone have any ideas?
Create a counter variable that you increment each time you find a non blank character and just loop through each subscript of the string with a for loop.
1 2 3 4 5 6 7 8 9
int count = 0;
string exampleString = "Test String Var";
for ( int i = 0; i < exampleString.length(); i++ )
{
if ( exampleString[i] != ' ' )
count++
}
yeah thanks it makes of sense. BUT when i input it into my program it compiles fine but i get a completely wroong answer wen i run it. i think it something wrong with my while loop. what you think it is?
string sentence;
int count;
int spacecount;
while (getline (cin, sentence))
{cout<<"you have entered["<<sentence<<"]\n;
for(int i= 0; i<sentence.length(); i++)
{if (sentence[i] != ' ')
spacecount++;
}
cout<<"number of non blank characters is: "<<spacecount<<endl;
cout<<"number of lines entered is: "<<count<<endl;
In your program you count the number of items that are NOT spaces yet you are incrementing a variable called spacecount++ which is backwards. Change the != to ==. Or study this other thread and do it with std::count.
thanks kempo!. One last question tho.... How do i count length of longest line and number of times longest line occurs and include that in my program above?
Ive written the pseudocode for it but i dont know the algorithim functions to use.. my pseudocode is as follows:
current length = length()
if current length = max length
longest line counter = longets line counter +1
else if curresnt length > maxlength
maxlength = current length
longest line length resets to 1
cool, so maxlength is an integer variable? what will this code solve... if its the longest line from a series of strings entered? or how manytimes it occurs?
eker676 is just giving you an if statement that you would include to identify the length of the longest line. To count the number of lines with that length you would also have to have an array that would keep track of all line lengths so that you could subsequently count how many occurrences of that length occur.
The previous thread showed you how to use std::count. std::max_element can help you as well. Each time you receive a new input string push its size into a std::vector container with push_back. When the while loop ends, you can use the aforementioned algorithms to determine the max_element and then count the number of times that the value occurs in the container.