/* * strings.cpp * * Created on: 12.11.2013 * Author: trifon */ #include #include using namespace std; void string_io() { // !!! char s[5] = { 'H', 'e', 'l', 'l', 'o' }; char word[6] = "Hello"; int a[5] = { 1, 2, 3, 4, 5 }; cout << word << endl; cout << a << endl; // cout << s << endl; // !!! cin >> a; cin >> word; // до разделител!!!! cout << word << endl; char sentence[100]; cin.getline(sentence, 100); cout << sentence << endl; // ръчно извеждане на низ int i = 0; // лошо, но вярно: while(sentence[i]) { while(sentence[i] != '\0') { cout << sentence[i]; i++; } cout << endl; } void string_functions() { char s[] = "Hello, world!"; cout << strlen(s) << endl; // Лошо: for(int i = 0; i < strlen(s); i++)... // Хубаво: // int l = strlen(s) // for(int i = 0; i < l; i++)... char s2[14] = "Empty"; cout << strcpy(s2, s) << endl; // strcpy връща s2 cout << strcmp(s, s2) << endl; cin.getline(s2, 14); if (strcmp(s, s2) < 0) cout << s << " е преди " << s2 << endl; else cout << s2 << " е преди " << s << endl; /* * Грешно! if (strcmp(s,s2)) cout << s << " съвпада с " << s2 << endl; */ /* * Правилно: if (strcmp(s,s2) == 0) cout << s << " съвпада с " << s2 << endl; */ cout << strcat(s2, "!!!") << endl; // !!! дали в s2 има достатъчно място! if (strchr(s2, 'b')) cout << "Среща се b!" << endl; if (strstr(s2, "bye")) cout << "Среща се bye!" << endl; } void palindrome() { char s[100]; cin.getline(s, 100); int l = strlen(s); int i = 0, j = l - 1; while (i < j && s[i] == s[j]) { i++; j--; } // НЕ - s[i] != s[j] // ДА - i >= j cout << "Низът " << s; if (i < j) cout << " НЕ"; cout << " е палиндром!" << endl; } // ' ', '.', ',', '!' '?' ';' void count_words() { int words = 0; char s[100]; cin.getline(s, 100); int l = strlen(s); bool word = false; for(int i = 0; i < l; i++) { bool new_word = s[i] != ' ' && s[i] != '.' && s[i] != ',' && s[i] != '!' && s[i] != '?' && s[i] != ';' && s[i] != ':'; if (!new_word && word) { word = false; } else if (new_word && !word) { word = true; words++; } } cout << "Брой на думите: " << words << endl; /* 1. i < l - 1 2. i < l 3. i <= l 4. i <= l - 1 5. i < l + 1 */ } void calculator() { char s[100]; cin.getline(s, 100); int l = strlen(s); int result = 0, n = 0; char op = '+'; for(int i = 0; i < l; i++) { if (s[i] >= '0' && s[i] <= '9') { // Трик за преобразуване на символ в цифра int d = s[i]-'0'; // n *= 10 += d; n = n * 10 + d; } else { switch(op) { case '+': result += n;break; case '-': result -= n;break; case '*': result *= n;break; case '/': result /= n; } op = s[i]; n = 0; } } cout << "Result = " << result << endl; } int main() { //string_io(); // string_functions(); // palindrome(); // count_words(); calculator(); return 0; }