c++ - 如何检查空行?

标签 c++ arrays matrix ifstream

我的 input.txt 文件:

4

4

5 0 1 2
1 4 0 0
1 1 5 4
0 6 3 2

0 4 1 2
1 7 5 0
2 3 5 6
0 6 2 2

1:0 4 2 0

我现在的计划:

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <sstream>
using namespace std;

int main()
{
ifstream File("input.txt");
string line;
string num;
string array[50];
string comma;
int i=0;
    while (getline(File,line)) {

        comma="";
        istringstream s(line);

        if (line.empty()){

            comma=",";
            s >> num ;
            array[i] =  comma;
        }

        else {
            s >> num ;
            array[i] =  num;
        }
        i++;

    }        
return 0;
}

嗯,我的程序没有给我想要的东西!当我打印 array[i] 时,它只给我第一列中的数字!像这样:

4
,
4
,
5
3
1
7
,
0
1
2
6
,
1:0

我想做的是在有空行的地方放一个逗号,这样我就可以区分这些数字并将它们存储在一个intger数组中以在它们之间执行数学运算

解释我的 input.txt 文件:

numbers and matrix size inside input file can be changed by me.

4 <= #number of items 

4 <= #types of items

5 0 1 2 <= matrix #1
1 4 0 0
1 1 5 4
0 6 3 2

0 4 1 2 <= matrix #2
1 7 5 0
2 3 5 6
0 6 2 2

1:0 4 2 0 <= Available numbers for item #1 

我想:

  1. 在变量中存储项目数。

  2. 将项目类型存储在变量中。

  3. 矩阵#1矩阵#2 存储在一个2 数组 中并进行减法矩阵#1 和矩阵#2 之间。

这可以做到吗?或者有没有更简单的方法来区分这些数字并将它们存储在变量和内部数组中?

最佳答案

问题很简单。

你读取了一行数据

while (getline(File,line)) {

但是你只处理该行中的一个元素:

    if (line.empty()) {
        ...
        s >> num ;
        ...
    }
    else {
        s >> num ;
    }

你只需要把 if ... else语句进入某种循环。

另外,我不明白那个 if 的第一个分支语句:如果line是空的,s 中不应该有任何东西阅读。

因此,稍微编辑一下,这应该更接近您正在寻找的内容(我还没有尝试过看看它是否真的有效):

    ...
    while (getline(File,line)) {
        if (line.empty()) {
            array[i] = ","
            ++i;
            continue;
        }
        istringstream s(line);

        while(s >> num) {
            array[i] =  num;
            ++i;
        }
    }        
    return 0;
}

关于c++ - 如何检查空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34244521/

相关文章:

c++ - 类的 vector 不存储单独的纹理

arrays - 如何将来自Perl正则表达式的捕获存储到单独的变量中?

matlab - 如何在 MATLAB 中删除矩阵的对角线元素?

matlab - 在MATLAB中绘制一系列2D黑白图

arrays - 在Matlab中直接获取数组/单元格的元素

c++ - 获取内存地址的值

c++ - 标准 :ostream and cross-platform compatibility

c++ - C++ 中 const list<t> 的迭代器

c - 使用固定大小的数组时的垃圾值,而如果使用动态大小的数组,则结果正确

Python 数组解析