简体   繁体   中英

How To Check empty Lines?

my input.txt file:

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

my program for now:

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

well, my program is not giving me what I want! when I print the array[i] its giving me only the numbers in the first Column! like this :

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

what i want to do is to put a comma where ever there is an empty line , so I can distinguish between these numbers and store them inside an intger array to do mathematical operations between them .

to explain my input.txt file:

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 

and I want to :

  1. store number of items inside a variable.

  2. store types of items inside a variable.

  3. store matrix #1 and matrix #2 inside a an 2 arrays and do Subtraction between matrix #1 and matrix #2.

Can this be done ? or is there any easier method to distinguish between these numbers and store them inside variables and an inter array ?

The problem is simple.

You read a line of data with

while (getline(File,line)) {

But then you only process one element from that line:

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

You simply need to put that if ... else statement into some kind of loop.

Additionally, I don't understand the first branch of that if statement: if line is empty, there shouldn't be anything in s to read from.

So, slightly edited, this should be closer to what you're looking for (I haven't tried this to see if it actually works):

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM