0

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);
1
  • 2
    Read one char at a time. Stop when you have 8. Commented Feb 9, 2019 at 13:18

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

}

1 Comment

Why are you recommending a C solution to a C++ question? std::cin has get() methods for reading single chars, and read() methods for reading char arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.