gpt4 book ai didi

c++ - 如何将不同长度的数据读入二维数组?

转载 作者:行者123 更新时间:2023-11-28 04:51:56 24 4
gpt4 key购买 nike

如题,如何将不同长度的数据读入二维数组?而且我知道每行数据长度的上限。喜欢..

5 6 9 8 4

5 4 9 5 6 5

1 2 3

4 5

我想将这些数据输入到二维数组的每一行中,但是 c++ 的 cin 会跳过 '\n' 的输入

所以下面的方法是行不通的

for(int i=0; i<m; i++)
{
int ch=0;
while( (cin >> ch)!='\n' )
{
element[i][ch] = true;
}
}

那么,我该如何解决这个问题呢?或者,我如何区分'\n'?让我的“同时”知道这一点。非常感谢。

最佳答案

使用 std::getline() 将一行读入字符串。从中创建一个 std::stringstream,然后将每个数字读入一个数组元素。

std::string line;
int row = 0;
while(std::getline(cin, line)) {
std::stringstream linein(line);
int num;
int col = 0;
while (linein >> num) {
element[row][col++] = num;
}
row++;
}

关于c++ - 如何将不同长度的数据读入二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48013182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com