Вот код, который я написал:
Код: Выделить всё
template
vector read2DVectorFromStdin() {
string input;
getline(cin, input);
// Remove all spaces from the input
input.erase(remove_if(input.begin(), input.end(), ::isspace), input.end());
vector matrix;
stringstream ss(input);
char ch;
// Check if input starts and ends with square brackets
if (input.front() != '[' || input.back() != ']') {
cerr ch) {
if (ch == '[') {
vector row;
T value;
string token;
while (ss.peek() != ']') {
getline(ss, token, ',');
// Handle the case where the token ends with ']'
size_t pos = token.find(']');
if (pos != string::npos) {
token = token.substr(0, pos);
}
stringstream tokenStream(token);
if constexpr (is_same::value) {
// Remove leading and trailing spaces
token.erase(remove_if(token.begin(), token.end(), ::isspace), token.end());
// Check for and remove quotes
if (token.front() == '"' && token.back() == '"') {
token = token.substr(1, token.length() - 2);
}
row.push_back(token);
}
else if constexpr (is_same::value) {
// Convert to lowercase for easier comparison
transform(token.begin(), token.end(), token.begin(), [](unsigned char c) { return tolower(c); });
// Trim leading and trailing spaces
auto start = token.find_first_not_of(' ');
if (start != string::npos) {
token = token.substr(start);
}
auto end = token.find_last_not_of(' ');
if (end != string::npos) {
token = token.substr(0, end + 1);
}
if (token == "true" || token == "1") {
value = true;
}
else if (token == "false" || token == "0") {
value = false;
}
else {
cerr
Подробнее здесь: [url]https://stackoverflow.com/questions/78730909/c-generic-function-to-read-2d-vector-from-standard-input[/url]