c++ - 将用户输入的空间存储在 char 数组中

标签 c++ arrays char

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

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`) 然后终止。我将如何将输入(包括空格字符)直接存储到板中?

最佳答案

尝试更像这样的东西:

#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] = '\0';
}

关于c++ - 将用户输入的空间存储在 char 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39231937/

相关文章:

c++ - 我需要哪个 SDK 来确保 Visual Studio C++ 2017 中的 Windows 7 兼容性

java - 拆分字节数组以映射 java 类对象中的字段的有效方法

java - 将字符串更改为 Char 数组

字符比较错误输出并且在C中没有比较

php - 如何将两个四元数相乘

c++ - cout 的宽度 - 显示

javascript:匹配方法返回对象而不是数组

javascript - 数组 : Convert table data to array by javascript

将 int 转换为 char* C

c++ - 使用 openssl c/c++ API 解密失败