【问题标题】:C++ How to Input multiple values on one line in a text fileC ++如何在文本文件的一行中输入多个值
【发布时间】:2015-07-12 06:56:51
【问题描述】:

快速的问题,也许是一个简单的问题。我还没有用 C++ 编写代码,但我正在为一个朋友制作一个小程序。该程序只是获取一个文本文件并将其输入到一个简单的二维数组中。

表格或二维数组结构如下: 4 6 1 5 2 34 13 1 42 9 34 11 5 -1 12 8 20 1 25 0 9 6 17 23 5 1

第一个数字是行,第二个数字是列,然后在这两个数字之后我们得到实际的表格。

我能够将前两个数字正确输入到 RowCount 和 ColumnCount 中,但是我该如何将实际的表放入数组中?

这是我目前所拥有的,我知道我需要在获得 rowCount 和 colCount 后正确设置数组,但是之后我将如何将表输入到数组中?

// Importing the information Function
void importTable(string filePath, int** &table, int &rowCount, int &colCount){

ifstream fileInput;
filePath = filePath + ".txt";
fileInput.open(filePath.c_str());

if(fileInput != NULL){
        fileInput >> rowCount;
        fileInput >> colCount;
        // Setup the Array
        for(int i = 0; i < rowCount; i++){
            table[i] = new int[colCount];
        }

        fileInput.close();

} else {
    cout << filePath << " is missing or does not exist, try again" << endl;
}
}

// Main Function
int main() {
int rowCount = 0;
int colCount = 0;
int **table;
table = new int*[rowCount];

int *rowCountP = &rowCount;
int *colCountP = &colCount;

string filePath = "";

cout << "Enter the filepath name: " << endl;
cin >> filePath;
cout << endl;

importTable(filePath, table, rowCount, colCount);
cout << rowCount << colCount;

return 0;
}

【问题讨论】:

    标签: c++ arrays


    【解决方案1】:

    使用std::stringstream,并通过从流中读取值来分配数组元素。

    您的语法看起来与How to split a space separated string into multiple strings in C++? 非常相似,但您必须将读取的每个字符串转换为数字(例如,使用atoi())。

    【讨论】:

      猜你喜欢
      • 2020-03-09
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      相关资源
      最近更新 更多