Jommiey

Lektion4

Nov 28th, 2018
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. //---------
  2. //Uppgift 1
  3. //---------
  4. #include <iostream>
  5. #include <string>
  6.  
  7. int main(){
  8.   std::string str{};
  9.   int x{};
  10.  
  11.   std::cout << "Mata in: ";
  12.   std::cin >> x;
  13.  
  14.   if(!std::cin)
  15.   {
  16.     std::cin.clear();
  17.     std::cin >> str;
  18.   }
  19.  
  20.   std::cout << str << std::endl;
  21.   std::cout << x << std::endl;
  22. }
  23. //Försöker läsa in till x. Om det inte funkar så sätts flagga och vi går in
  24. //i if-satsen och clearar cin och sätter str till cin.
  25.  
  26. //---------
  27. //Uppgift 2
  28. //---------
  29. #include <iostream>
  30. #include <fstream>
  31.  
  32. int main()
  33. {
  34.   std::ifstream ifs{"statistics.txt"};
  35.  
  36.   if ( ! ifs )
  37.   {
  38.      std::cerr << "Kunde inte öppna 'statistics.txt'." << std::endl;
  39.      return 1; // terminate program with error code 1
  40.   }
  41.  
  42.   double nr;
  43.   double sum{0.0};
  44.   int count{0};
  45.   while ( ! ifs.eof() )
  46.   {
  47.      ifs >> nr;
  48.      sum += nr;
  49.      ++count;
  50.      std::cout << "xd" << std::endl;
  51.   }
  52.   std::cout << nr << ", " << sum << ", " << count << std::endl;
  53.   double average = sum / (count-1);
  54.   std::cout << average << std::endl;
  55.   return 0;
  56. }
  57. //Count räknar en extra eftersom vi läser in ifs inuti loopen som kollar
  58. //om den är eof. Gör vi count-1 i average uträkningen så får vi rätt.
  59.  
  60. //---------
  61. //Uppgift 3
  62. //---------
  63. #include <iostream>
  64.  
  65. int main(){
  66.   std::cout << "Mata in ett flyttal: ";
  67.   double d;
  68.   std::cin >> d;
  69.  
  70.   if (!std::cin){
  71.     std::cerr << "Måste vara ett flyttal. T.ex 10.2."
  72.     std::cin.clear();
  73.   }
  74.  
  75.   std::cout << d << std::endl;
  76.   return 0;
  77. }
  78.  
  79. //---------
  80. //Uppgift 8
  81. //---------
  82. #include <algorithm>
  83. #include <iostream>
  84. #include <vector>
  85.  
  86. using namespace std;
  87. int main(){
  88.   vector<int> v{1, 7, 2, 3, 7, 8, 7, 2, 4, 3, 8, 1};
  89.   int c = count(v.begin(), v.end(), 1);
  90.  
  91.   for (int i = 0; i < c; ++i)
  92.   {
  93.     auto it{find(v.begin(), v.end(), 1)};
  94.     v.erase(it);
  95.   }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment