fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. #include <cctype> // Untuk fungsi isupper, islower, isdigit
  5.  
  6. std::map<std::string, int> hitungAtomSederhana(const std::string& rumus) {
  7. std::map<std::string, int> hitungan;
  8. int n = rumus.length();
  9.  
  10. for (int i = 0; i < n; ++i) {
  11. // 1. Identifikasi Unsur
  12. if (isupper(rumus[i])) {
  13. std::string unsur = "";
  14. unsur += rumus[i];
  15.  
  16. // Cek jika ada huruf kecil setelah huruf kapital (misal: He, Mg)
  17. if (i + 1 < n && islower(rumus[i+1])) {
  18. unsur += rumus[i+1];
  19. i++; // Maju satu karakter lagi
  20. }
  21.  
  22. // 2. Identifikasi Angka
  23. std::string strAngka = "";
  24. int j = i + 1;
  25. while (j < n && isdigit(rumus[j])) {
  26. strAngka += rumus[j];
  27. j++;
  28. }
  29.  
  30. int jumlah = (strAngka == "") ? 1 : std::stoi(strAngka);
  31. hitungan[unsur] += jumlah;
  32.  
  33. i = j - 1; // Sesuaikan indeks loop utama
  34. }
  35. }
  36. return hitungan;
  37. }
  38.  
  39. int main() {
  40. std::string rumus1 = "H2O";
  41. std::string rumus2 = "C6H12O6";
  42.  
  43. std::cout << "Rumus: " << rumus2 << std::endl;
  44. std::map<std::string, int> hasil = hitungAtomSederhana(rumus2);
  45.  
  46. for (const auto& pair : hasil) {
  47. std::cout << pair.first << ": " << pair.second << std::endl;
  48. }
  49.  
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
Rumus: C6H12O6
C: 6
H: 12
O: 6