如何決議輸入,例如:
[[1,3,5,7],[10,11,16,20],[23,30,34,60]]
對于m x n大小的二維向量。我試過了
char x;
vector<int> v;
vector<vector<int>> v_v;
vector<int> temp;
int br_op_cl = 0;
int row = 0;
while (cin >> x) {
// cout << x << endl;
if (x == '[' || x == '{') {
// cout << "inside [" << endl;
br_op_cl ;
cout << "inside [ " << br_op_cl << endl;
} else if (x == ']' || x == '}') {
cout << "inside ] " << x << endl;
br_op_cl--;
} else if (x >= 0 && x != ',') {
cout << "inside 0-9 " << x << endl;
temp.push_back(x);
if (br_op_cl % 2 != 0) {
cout << br_op_cl << " inside br_op_cl " << '\n';
v_v.push_back(temp);
}
}
}
輸出是
49 51 53 55 49 48 49 49 49 54 50 48 50 51 51 48 51 52 54 48
這是每個數字的ascii值。有關如何在 C 中一起讀取 chars 和 int 以及決議技術的任何幫助
uj5u.com熱心網友回復:
考慮[1,3,5,7]為單行。使用stringstream讀取此行。然后使用另一個stringstream讀取該行的內容。
getline將讀取每一行直到命中],另一個getline將讀取每一列直到命中]。
替換出現的{ with [, 使決議更容易。
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
int main()
{
std::string str = "[[1,3,5,7],[10,11,16,20],[23,30,34,60]]";
replace(str.begin(), str.end(), '{', '[');
replace(str.begin(), str.end(), '}', ']');
std::stringstream ss(str);
std::vector<std::vector<int>> res;
if (ss.get() != '[')
return 0;
char c;
while (ss >> c && c != ']') {
if (c == '[') {
getline(ss, str, ']');
std::stringstream scol(str);
std::vector<int> vec;
while (getline(scol, str, ','))
vec.push_back(std::stoi(str));
res.push_back(vec);
}
}
for (auto& row : res) {
for (auto& col : row) std::cout << col << ",";
std::cout << "\n";
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/327453.html
上一篇:模式匹配不允許我更改值
