Guest User

Untitled

a guest
Jan 19th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. int main(int argc,char **argv)
  5. {
  6.     using namespace std;
  7.  
  8.     string tmp;                                         //LT: Laikinas string skirtas laikyti vartotojo ivesta skaiciu.
  9.                                                         //EN: Temporary string to keep a number from the input.
  10.     if (argc > 1)  
  11.     {                                                   //LT: Jei vartotojas ivede skaiciu kaip argumenta komandu eiluteje, ji naudoti.
  12.         tmp = argv[1];                                  //EN: If the user typed the number as an argument in the command line, use it.
  13.     }
  14.     else
  15.     {
  16.         cout << "Prasome ivesti skaiciu: ";             //LT: Jei ne, prasyti vartotojo ivesti skaiciu.
  17.         cin >> tmp;                                     //EN: Otherwise, ast the user for a number.
  18.     }
  19.  
  20.     int result = 0;                                     //LT: int skirtas laikyti gautai sumai.
  21.                                                         //EN: int to hold the result.
  22.     for(int i = 0; i < tmp.length(); i++)               //LT: Tikrina kiekviena char'a string'e.
  23.     {                                                   //EN: Checks every char in the string.
  24.         if (tmp[i] >= 48 && tmp[i] <= 57)               //LT: Tikrina ar charas yra skaicius.
  25.         {                                               //EN: Checks if the char is a number.
  26.             result += static_cast<int>(tmp[i])-48;      //LT: Jei taip, ji konvertuoja i int. Cia atimama 48, nes char'ai i int'us tieciogiai nesivercia, int'as gaunasi char'o ascii kodas, kodai 48-57 yra 0-9, todel as is kodo atimu 48 kad gaut ivesta skaiciu.
  27.         }                                               //EN: If so, it converts it to an int. Here I subtract 48, because chars don't normally cast to ints, the int ends up being the chars ascii code, codes 48-57 are 0-9, so I subtract 48 to get the inputed number.
  28.     }
  29.    
  30.     cout << result;                                     //LT: Galiausia, ekrane pasirodo rezultatas!
  31.                                                         //EN: Finally, the result shows up on screen!
  32.     cin.clear();
  33.     cin.ignore(255, '\n');                              //LT: Kad programa neisijungtu vartotojui nespejus perskaityti rezultato, programa palaukia kol vartotojas ka nors paspaus, ir tik tada issijungia.
  34.     cin.get();                                          //EN: The program waits for input before finishing, so the user has time to read the result.
  35.     return 0;
  36. }
Add Comment
Please, Sign In to add comment