从char数组中的用户输入存储空间

时间:2016-08-30 15:44:38

标签: 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行(当row3 3时),然后终止。我如何将输入(包括空格字符)直接存入电路板?

2 个答案:

答案 0 :(得分:1)

尝试更像这样的事情:

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

答案 1 :(得分:0)

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