需要帮助上传以逗号,空格和制表符分隔的文件

时间:2015-09-09 06:08:30

标签: c++ parsing ifstream

我正在阅读一个看起来像这样的文件:

4

1 2 3,4

4, 5,     6 7

  8.0, 9, 10,    11, 8.0, 9, 10,          11

当我尝试将其制作成4x4矩阵时,它看起来像这样:

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;

期望的输出:

1 2 3 4

4 5 6 7

8.0 9 10 11

8.0 9 10 11

1 个答案:

答案 0 :(得分:0)

当您读入字符串时,它会在遇到空格时停止。为了解决您的问题(因为您有无限逗号),首先逐行读取文件,将所有出现的逗号替换为空格,然后将其转换为向量。例如

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);
}