C++ 需要帮助上载由逗号、空格和制表符分隔的文件吗

C++ 需要帮助上载由逗号、空格和制表符分隔的文件吗,c++,parsing,ifstream,C++,Parsing,Ifstream,我正在读取一个文件,该文件如下所示: 4 1 2 3,4 4, 5, 6 7 8.0, 9, 10, 11, 8.0, 9, 10, 11 1 2 3,4 4, 5, 6 7 8.0, 9, 10, 11, 8.0, 9, 10, 11 11 当我尝试将其制作成4x4矩阵时,它看起来如下所示: 4 1 2 3,4 4, 5, 6 7 8.0, 9, 10, 11, 8.0, 9, 10, 11 1 2

我正在读取一个文件,该文件如下所示:

4

1 2 3,4

4, 5,     6 7

  8.0, 9, 10,    11, 8.0, 9, 10,          11
1 2 3,4 4,

5, 6 7 8.0,

9, 10, 11, 8.0,

9, 10, 11 11
当我尝试将其制作成4x4矩阵时,它看起来如下所示:

4

1 2 3,4

4, 5,     6 7

  8.0, 9, 10,    11, 8.0, 9, 10,          11
1 2 3,4 4,

5, 6 7 8.0,

9, 10, 11, 8.0,

9, 10, 11 11
如何从文件中获取输入以忽略逗号,并将其作为分隔符包含在矩阵中的空白处

//Declared variables
string filename;
int rows = 0;
string value;

//Declared file objects
ifstream data_input;

//Prompts user for filename
cout << "Please enter the name of the file that you would like to upload.\n";
cin >> filename;

//Opens the file.
data_input.open(filename);

//Set total number of rows and total number of columns for Matrix A
data_input >> rows;
int columns = rows;
vector<vector<string>> matrix(rows, vector<string>(columns));

//Goes through each row
for (int i = 0; i<rows; i++)
{
    //Goes through each column
    for (int j = 0; j<columns; j++)
    {
        //Sets values to a matrix
        data_input >> value;
        matrix[i][j] = value;
    }
}

//Prints out matrix
cout << "--------Matrix--------\n";
for (int i = 0; i<rows; i++)
{
    //Goes through each column
    for (int j = 0; j<columns; j++)
    {
        //Prints out each individual value of Matrix A
        cout << matrix[i][j] << "\t";
    }
    cout << endl;
}

system("pause");
system("cls");
return 0;
期望输出:

1234

4 5 6 7

8.0 9 10 11


8.0 9 10 11

当您读入字符串时,遇到空格时,它将停止。要解决逗号不定的问题,请先逐行读取文件,将所有出现的逗号替换为空格,然后将其转换为向量。比如说

vector<vector<string>> matrix;
std::ifstream in(filename);
std::string line;
int rows;
in >> rows;
while (std::getline(in, line)) {
    std::replace(line.begin(), line.end(), ',', ' ');
    std::stringstream ss(line);
    std::istream_iterator<std::string> begin(ss);
    std::istream_iterator<std::string> end;
    std::vector<std::string> vstrings(begin, end);
    matrix.push_back(vstrings);
}

请把你的问题说清楚。我不清楚你想要的结果是什么,请提供一个例子。另外,你看似错误的输出包含11 11,我无法从你的输入中读取。此外,用逗号分隔的值和忽略其他逗号对我来说是相当混乱的;4 5 6 7 ; 8.0 9 10 11; 8.0 9 10 11 ; 我相信您所说的11 11只是从文件中读取的最后一个值,并将其设置为矩阵[4][4]上的最后一个位置。我的问题现在有意义了吗?