Search code examples
c++stringstring-length

how to get a string input from user with pre-defined string length in C++?


I am trying to get a string with 8 characters long from the user. User have to enter the string continuously. Once the string reaches 8 characters, it has to go next line of the code.

I've already tried with Arrays, and loops. But, It requires the user to hit enter after getting each character.

string str;
int b;
std::cin>>str.length(8);

Solution

  • This can be done many different ways.

    Try this

    std::string str;
    str.resize(8);
    for (int i = 0; i < 8; ++i)
        std::cin >> str[i];
    

    Or

    std::string str;
    str.resize(8);
    for (int i = 0; i < 8; ++i)
        str[i] = std::cin.get();
    

    Or

    std::string str;
    str.resize(8);
    std::cin.read(&str[0], 8);
    

    Or

    char arr[9];
    std::cin >> std::setw(9) >> arr;
    std::string str(arr, 8);