Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //---------
- //Uppgift 1
- //---------
- #include <iostream>
- #include <string>
- int main(){
- std::string str{};
- int x{};
- std::cout << "Mata in: ";
- std::cin >> x;
- if(!std::cin)
- {
- std::cin.clear();
- std::cin >> str;
- }
- std::cout << str << std::endl;
- std::cout << x << std::endl;
- }
- //Försöker läsa in till x. Om det inte funkar så sätts flagga och vi går in
- //i if-satsen och clearar cin och sätter str till cin.
- //---------
- //Uppgift 2
- //---------
- #include <iostream>
- #include <fstream>
- int main()
- {
- std::ifstream ifs{"statistics.txt"};
- if ( ! ifs )
- {
- std::cerr << "Kunde inte öppna 'statistics.txt'." << std::endl;
- return 1; // terminate program with error code 1
- }
- double nr;
- double sum{0.0};
- int count{0};
- while ( ! ifs.eof() )
- {
- ifs >> nr;
- sum += nr;
- ++count;
- std::cout << "xd" << std::endl;
- }
- std::cout << nr << ", " << sum << ", " << count << std::endl;
- double average = sum / (count-1);
- std::cout << average << std::endl;
- return 0;
- }
- //Count räknar en extra eftersom vi läser in ifs inuti loopen som kollar
- //om den är eof. Gör vi count-1 i average uträkningen så får vi rätt.
- //---------
- //Uppgift 3
- //---------
- #include <iostream>
- int main(){
- std::cout << "Mata in ett flyttal: ";
- double d;
- std::cin >> d;
- if (!std::cin){
- std::cerr << "Måste vara ett flyttal. T.ex 10.2."
- std::cin.clear();
- }
- std::cout << d << std::endl;
- return 0;
- }
- //---------
- //Uppgift 8
- //---------
- #include <algorithm>
- #include <iostream>
- #include <vector>
- using namespace std;
- int main(){
- vector<int> v{1, 7, 2, 3, 7, 8, 7, 2, 4, 3, 8, 1};
- int c = count(v.begin(), v.end(), 1);
- for (int i = 0; i < c; ++i)
- {
- auto it{find(v.begin(), v.end(), 1)};
- v.erase(it);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment