Mahmud Adam Mahmud Adam - 3 months ago 17
C++ Question

Storing space from user input in char array

I am trying to store space

' '
as a recognized character directly into an array of chars by doing this:

char ** board = new char *[row];
for (int r = 0; r < row; r++) {
board[r] = new char[col];
}

for (int r = 0; r < row; r++) {
cout << "Enter input: " << endl;
cin >> board[r];

}


But if I enter
' '
into the console it executes the
Enter input
line twice (when
row
is
3
3`) and then terminates. How would I go about storing input (including space character) directly into board?

Answer

Try something more like this:

#include <iostream>
#include <iomanip>
#include <limits>

char ** board = new char *[row];
for (int r = 0; r < row; r++) {
    board[r] = new char[col];
}

for (int r = 0; r < row; r++) {
    std::cout << "Enter input: " << std::endl;
    std::cin >> std::noskipws >> std::setw(col) >> board[r];
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

However, as previously suggested in comments, you really should be using std::string and std::getline() instead. And if you can, change your array to std::vector<std::string>:

#include <iostream>
#include <vector>
#include <string>

std::vector<std::string> board(row);

for (int r = 0; r < row; r++) {
    std::cout << "Enter input: " << std::endl;
    std:getline(std::cin, board[r]);
}

If you cannot use std::vector, you can at least use std::string for reading the user's input and then copy its data into your char[][] array:

#include <iostream>
#include <string>
#include <cstring>

char ** board = new char *[row];
for (int r = 0; r < row; r++) {
    board[r] = new char[col];
}

for (int r = 0; r < row; r++) {
    std::cout << "Enter input: " << std::endl;
    std::string input;
    std::getline(std::cin, input);
    std::strncpy(board[r], input.c_str(), col-1);
    board[r][col-1] = '\0';
}
Comments