将用户输入的 space 存储在 char 数组中

Storing space from user input in char array

我试图通过这样做将 space ' ' 作为可识别的字符直接存储到字符数组中:

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

}

但是如果我在控制台中输入 ' ' 它会执行 Enter input 行两次(当 row33` 时)然后终止。我如何将输入(包括 space 字符)直接存储到板中?

您的问题是控制台无法将 ' ' 识别为有效输入,因此它会再次询问。我不知道用 get()getline() 代替 cin 是否可行,但您需要找到一种方法让控制台将空格作为输入,或者您可以创建某种过滤器以便您的程序将特殊字符识别为空格并存储它是这样的。希望有帮助

试试像这样的东西:

#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');
}

但是,正如之前在评论中建议的那样,您确实应该改用 std::stringstd::getline()。如果可以,请将数组更改为 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]);
}

如果您不能使用 std::vector,您至少可以使用 std::string 来读取用户的输入,然后将其数据复制到您的 char[][] 数组中:

#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] = '[=12=]';
}