c++ - Program to find the number of whitespaces and newlines characters -


how program find number of white spaces , newlines characters in c++ ?? have far....

#include <iostream.h> #include <string.h>  int main() {   int i;   int w = 0;   char a[] = {' ', '\n'};   char x[30],z[30];    (int = 0 ; <= 30;i++)     cin >> x[i];    (int j = 0 ; j < 30; j++) {     (int k = 0 ; k < 2; k++) {       x[j] == a[k];       if (x[j] == ' ')         w++;     }   }    cout << w << endl;   system("pause");   return  0; } 

here example showing fundamental algorithm. others have commented, there more simple , efficient methods.

int main(void) {   char c;   unsigned int space_quantity = 0;   unsigned int newline_quantity = 0;   while (cin >> c) // read in character.   {     switch (c)     {       case ' ':  //  check space.         ++space_quantity;         break;        case '\n':  // check newline.         ++newlines;         break;        default:  // don't other characters.         break;     }   }   cout << "spaces: " << space_quantity << '\n';   cout << "newlines: " << newline_quantity << '\n';   return exit_success; } 

in above program, used switch versus if-else-if because thought looked more readable. may not have learned switch statement, can use multiple if statements check characters. same intention; maybe same executable code , performance.

edit 1: using arrays
arrays can improve performance of i/o, reading more 1 character per input request. searching through memory faster reading input source (not memory input source).

if must use arrays, here example using arrays. in general arrays not used cin due slow response of user.

#define array_capacity 128  int main(void) {   char c;   unsigned int space_quantity = 0;   unsigned int newline_quantity = 0;   char         buffer[array_capacity];   while (cin.read(buffer, array_capacity))   {      // need number of characters      // read buffer.      const unsigned int characters_read = cin.gcount();       // process each character buffer.      (unsigned int = 0; < characters_read; ++i)      {        switch (c)        {          case ' ':  //  check space.            ++space_quantity;            break;           case '\n':  // check newline.            ++newlines;            break;           default:  // don't other characters.            break;        } // end: switch      } // end:   } // end: while   cout << "spaces: " << space_quantity << '\n';   cout << "newlines: " << newline_quantity << '\n';   return exit_success; } 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -