Sierra
Sierra

Reputation: 59

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);

Upvotes: 0

Views: 129

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596307

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);

Upvotes: 1

Shakil
Shakil

Reputation: 4630

This can be done in following way

char str[100], input;
int idx = 0;
while( scanf("%c", &input ) == 1 )  { 

    str[idx++] = input;
    if( idx >= 8 ) break; // or your desire length of string

}

Upvotes: 1

Related Questions