Can't seem to make my code read white-spaces

How can I change this to include white-spaces

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>
#include <string> 
using namespace std;

int main() {

     const size_t nchars = 8 ;
     
    string String8;
    
    cout << "Enter " << nchars << " non-whitespace characters: " ;
    while( String8.size() < nchars )
    {
        char d;
        cin >> d;
        String8.push_back(d) ;
        
}       
        
    cout << endl << String8 << '\n' ;
    cout << endl;
    
}   
Why are you wanting to read whitespace? The code you have given us implies there shouldn't be any whitespace. What exactly are you trying to accomplish here?
That's why I need help

I'm trying to make a code where the user inputs 8 characters including white spaces then make a string out of it then outputs the string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <string>
#include <cctype>

int main()
{
    const std::size_t nchars = 8 ; // number of characters to be input

    std::string str ;

    std::cout << "enter " << nchars << " characters (including whitespace characters): " ;
    while( str.size() < nchars ) // as long nchars characters haven't been added
    {
        char c ;
        // get() is an unformatted input function (does not skip leading whitespace)
        std::cin.get(c) ; // read in one char (may be whitespace)
        str += c ; // or: str.push_back(c) ; // and append it to the string
    }

    // print out all nchars characters (all characters that are in the string)
    // range based loop: http://www.stroustrup.com/C++11FAQ.html#for
    for( char c : str ) // for each character c in the string
    {
        // print the character
        if( std::isprint(c) ) std::cout << c ; // printable character, print it as it is
        else if( c == '\t' ) std::cout << "\\t" ; // tab character, print its escape sequence
        else if( c == '\n' ) std::cout << "\\n" ; // new line character, print its escape sequence
        else std::cout << "\\" << std::oct << int(c) ; // other unprintable character, print its octal escape sequence

        // also print its integer value
        std::cout << "  " << std::dec << int(c) << '\n' ;
    }
}
Topic archived. No new replies allowed.