我的 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 存储在一个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/