Home

ITA - Appunti Cpp 002 - IO

linux debian lmde cpp

Appunti 002 - IO

IO - Esempio base

#include <iostream>
#include <string>

int main() {
    std::string name;
    
    // std::cout serve per gestire l'output
    // con si <<  concatena
    // std::endl è un manipolatore, appende un \n e provoca il flush dello stream
    std::cout << "Ciao, come ti chiami ?" << std::endl;

    // std::cout serve per gestire l'input
    std::cin >> name;

    std::cout << "Benvenuto " << name << std::endl;
    
    return 0;
}

IO - Leggere più valori

#include <iostream>
#include <string>

int main() {
    std::string name;
    int age;
    float h;
    
    
    std::cout << "Ciao, inserisci nome, età e altezza:" << std::endl;

    std::cin >> name >> age >> h;

    std::cout << "Benvenuto " << name << std::endl;
    std::cout << "Benvenuto " << name << " " << age << " " << h << std::endl;
    
    return 0;
}

IO - Cstyle input/output

#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include <limits>
 
int main()
{
    const char* s = "Hello";
    std::printf("Strings:\n"); // come std::puts("Strings:");
    std::printf("\t[%10s]\n", s);               // -->  [     Hello] 
    std::printf("\t[%-10s]\n", s);              // -->  [Hello     ]
    std::printf("\t[%*s]\n", 10, s);            // -->  [     Hello]
    std::printf("\t[%-10.*s]\n", 4, s);         // -->  [Hell      ]
    std::printf("\t[%-*.*s]\n", 10, 4, s);      // -->  [Hell      ]
 
    std::printf("Characters:\t%c %%\n", 'A');
 
    std::printf("Integers:\n");
    std::printf("\tDecimal: \t%i %d %.6i %i %.0i %+i %i\n", 1, 2, 3, 0, 0, 4, -4);
    std::printf("\tHexadecimal:\t%x %x %X %#x\n", 5,10,10,  6);
    std::printf("\tOctal: \t%o %#o %#o\n", 10, 10, 4);
 
    std::printf("Floating point:\n");
    std::printf("\tRounding:\t%f %.0f %.32f\n", 1.5, 1.5, 1.3);
    std::printf("\tPadding:\t%05.2f %.2f %5.2f\n", 1.5, 1.5, 1.5);
    std::printf("\tScientific:\t%E %e\n", 1.5, 1.5);
    std::printf("\tHexadecimal:\t%a %A\n", 1.5, 1.5);
    std::printf("\tSpecial values:\t0/0=%g 1/0=%g\n", 0.0/0.0, 1.0/0.0);
 
    std::printf("Variable width control:\n");
    std::printf("\tright-justified variable width: '%*c'\n", 5, 'x');
    int r = std::printf("\tleft-justified variable width : '%*c'\n", -5, 'x');
    std::printf("(the last printf printed %d characters)\n", r);
 
    std::printf("Fixed-width types:\n");
    std::uint32_t val = std::numeric_limits<std::uint32_t>::max();
    std::printf("\tLargest 32-bit value is %" PRIu32 " or %#" PRIx32 "\n", val, val);
}

Riferimenti