Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- int main(int argc,char **argv)
- {
- using namespace std;
- string tmp; //LT: Laikinas string skirtas laikyti vartotojo ivesta skaiciu.
- //EN: Temporary string to keep a number from the input.
- if (argc > 1)
- { //LT: Jei vartotojas ivede skaiciu kaip argumenta komandu eiluteje, ji naudoti.
- tmp = argv[1]; //EN: If the user typed the number as an argument in the command line, use it.
- }
- else
- {
- cout << "Prasome ivesti skaiciu: "; //LT: Jei ne, prasyti vartotojo ivesti skaiciu.
- cin >> tmp; //EN: Otherwise, ast the user for a number.
- }
- int result = 0; //LT: int skirtas laikyti gautai sumai.
- //EN: int to hold the result.
- for(int i = 0; i < tmp.length(); i++) //LT: Tikrina kiekviena char'a string'e.
- { //EN: Checks every char in the string.
- if (tmp[i] >= 48 && tmp[i] <= 57) //LT: Tikrina ar charas yra skaicius.
- { //EN: Checks if the char is a number.
- 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.
- } //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.
- }
- cout << result; //LT: Galiausia, ekrane pasirodo rezultatas!
- //EN: Finally, the result shows up on screen!
- cin.clear();
- cin.ignore(255, '\n'); //LT: Kad programa neisijungtu vartotojui nespejus perskaityti rezultato, programa palaukia kol vartotojas ka nors paspaus, ir tik tada issijungia.
- cin.get(); //EN: The program waits for input before finishing, so the user has time to read the result.
- return 0;
- }
Add Comment
Please, Sign In to add comment