Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何从文件中传递二维拼图_C++_File - Fatal编程技术网

C++ 如何从文件中传递二维拼图

C++ 如何从文件中传递二维拼图,c++,file,C++,File,我在一个文件中有一个拼图,我试图将这个拼图传递到2D数组,但我无法确定新行,因此无法传递到新行。这是一个难题: 00 00 00 00 01 02 04 05 00 00 00 00 06 08 09 10 12 13 00 00 00 17 19 14 15 18 07 00 00 00 20 21 23 25 24 29 22 26

我在一个文件中有一个拼图,我试图将这个拼图传递到2D数组,但我无法确定新行,因此无法传递到新行。这是一个难题:

                00 00 00 00 01 02 04 05 00
                00 00 00 06 08 09 10 12 13
                00 00 00 17 19 14 15 18 07
                00 00 00 20 21 23 25 24 29
                22 26 28 35 34 31 33 38 39
                bb 30 31 34 32 36 03 11 16
我是这样读的:

string FileName;
fstream puzzle;
cout << "Please Enter the File Name : "  ;
cin >> FileName;
puzzle.open(FileName);
string s;
while(puzzle >> s){

    if(s == "bb"){
        arr[i][j] = 100;
        j++;
        counter++;
    }
    else{
        arr[i][j] = stoi(s);
        j++;
        counter++;
    }

}
字符串文件名;
流之谜;
cout>文件名;
puzzle.open(文件名);
字符串s;
while(拼图>>s){
如果(s==“bb”){
arr[i][j]=100;
j++;
计数器++;
}
否则{
arr[i][j]=stoi(s);
j++;
计数器++;
}
}

您可以逐行读取文件。在这种情况下,只需添加一个循环

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main() {
    std::string filename;
    std::cout << "Please Enter the File Name : ";
    std::cin >> filename;
    std::ifstream puzzle(filename);
    if(!puzzle.is_open()) {
        std::cout << "Can't open file" << '\n';
        return EXIT_FAILURE;
    }
    std::vector<std::vector<int>> arr;
    std::string line;
    while(std::getline(puzzle, line)) {
        arr.emplace_back();
        std::stringstream str(line);
        std::string s;
        while(str >> s) {
            if(s == "bb") {
                arr.back().emplace_back(100);
            } else {
                arr.back().emplace_back(std::stoi(s));
            }
        }
    }

    for (const auto &line : arr) {
        for (const auto &field : line) {
            std::cout << field << ' ';
        }
        std::cout << '\n';
    }
    return EXIT_SUCCESS;
}
#包括
#包括
#包括
#包括
#包括
int main(){
std::字符串文件名;
std::cout>filename;
std::ifstream拼图(文件名);
如果(!puzzle.is_open()){
标准::cout s){
如果(s==“bb”){
向后排列().向后放置(100);
}否则{
返回方位().emplace_back(std::stoi(s));
}
}
}
用于(常数自动和线路:arr){
用于(常量自动和字段:行){
std::cout 1)您可能会认为这样一种设计:在阅读拼图之前,您会说出行数和列数,例如,在本文件中为前2个数字2)您可以通过getline()逐行阅读这是
std::vector
的一个很好的用例。
std::vector
将在运行时动态扩展,当您在编译时不知道数据的大小时。数组需要在编译时知道它们的大小。