Search code examples
c++arrayscharcharacterlimit

Characters after a space is not being printed out


I was using character arrays to get inputs from the user then display the output afterwards. However, every time I enter values with spaces in between, only the first word before the space is printed.

For instance, this is what I typed:

Customer No.: 7877 323 2332

This will be the output:

Customer No.: 7877

I already searched for possible solutions but I can't seem to find the right solution.

This is my code for reference:

#include<iostream>
using namespace std;

int main()
{
    char custNum[10] = " ";  // The assignment does not allow std::string
    
    cout << "Please enter values for the following: " << endl;
    cout << "Customer No.: ";
    cin >> custNum;
    
    cout << "Customer No.: " << custNum << endl;
}

Solution

  • Another option is to use std::basic_istream::getline to read the entire string into the buffer and then remove the spaces with a simple for loop. But when using plain-old character arrays don't skimp on buffer size. It is far better to be 1000-characters too long than one-character too short. With your input, your absolute minimum size of custNum is 14 characters (the 13 shown plus the '\0' (nul-terminating) character. (rough rule-of-thumb, take your longest estimated input and double it -- to allow for user-mistake, cat stepping on keyboard, etc...)

    In you case you can simply do:

    #include <iostream>
    #include <cctype>
    
    int main() {
        
        char custNum[32] = " ";  // The assignment does not allow std::string
        int wrt = 0;
        
        std::cout << "Please enter values for the following:\nCustomer No.: ";
        
        if (std::cin.getline(custNum, 32)) {    /* validate every input */
        
            for (int rd = 0; custNum[rd]; rd++)
                if (!isspace((unsigned char)custNum[rd]))
                    custNum[wrt++] = custNum[rd];
            custNum[wrt] = 0;
            
            std::cout << "Customer No.: " << custNum << '\n';
        }
    }
    

    The two loop counters rd (read position) and wrt (write position) are simply used to loop over the original string and remove any whitespace found, nul-terminating again when the loop is left.

    Example Use/Output

    $ ./bin/readcustnum
    Please enter values for the following:
    Customer No.: 7877 323 2332
    Customer No.: 78773232332
    

    Also take a look at Why is “using namespace std;” considered bad practice? and C++: “std::endl” vs “\n”. Much easier to build good habits now than it is to break bad ones later... Look things over and let me know if you have questions.