Reading multiple columns in C++


 
Thread Tools Search this Thread
Top Forums Programming Reading multiple columns in C++
# 8  
Old 03-12-2013
awk.

Code:
awk FS="[ ,]" 'NR>1 {for(N=3; N<=NF; N++) $2+=$N;  $2 /= (NF-1); NF=2 } 1' inputfile

With explanation:

Code:
awk FS="[ ,]" # Separate columns on spaces and commas \
        'NR > 1 { # Do not try to do math on the first line with column names
                 for(N=3; N<=NF; N++) # Loop over column 3 to the last column, adding them to column 2 in turn
                         $2 += $N ;
                 $2 /= (NF-1); # Divide the column by 1-number of columns
                 NF=2; # Strip off all columns beyond the second
                 } 1 # Print all lines' inputfile

# 9  
Old 03-12-2013
Never a fan of strtok() or *scanf myself, debugging too many core dumps, I guess, especially in C++ (stateful subroutines in OO, ooooh!). I would fgets() lines into a char array and then process them as follows. If the byte is not a number part (strchr( " ,\t\n\r\f", this_char ), strchr( "1234567890-.", this_char) -- I like the positive test), set it to null and reset the in-number flag, else if it is, then if the in-number flag is not set, record the address in a char*[], increment the index on that array and set the in-number flag. When you are done, you have an array of pointers to null terminated character strings of numbers to atof() in the processing layer, with the index telling you the count of numbers found.

I would not read 4k into a 1k buf. fgets( buf, sizeof( buf ), stdin ) ?

Every fgets needs a "line too long" check to be stable. WHne this occurs, the last buffer byte is null and then preceeding one is not a line feed. Seed the buffer tail, rather than pawing over the line an additional time, for a quick check. Put it all in a nice subroutine p_fgets() (private fgets) with if ! fgets() if ferror() perror( "stdin" ); exit 1; else exit 0;

Last edited by DGPickett; 03-12-2013 at 03:19 PM..
# 10  
Old 03-12-2013
Quote:
Originally Posted by DGPickett
Never a fan of strtok() or *scanf myself, debugging too many core dumps, I guess, especially in C++ (stateful subroutines in OO, ooooh!).
It definitely has its flaws. Doing further editing on the string after it's tokenized is a bad idea. It's not re-entrant. And other such gripes.

But seeing your description of how you'd do it, particularly the 'set it to null', that's exactly what strtok does, to the letter. I don't see what makes your way better -- bigger program, slower program, bigger chance for bugs.

Same goes for sscanf. It makes some really complicated problems simple, and vice versa.

If the problem wasn't this simple though, I certainly wouldn't have used those.

Last edited by Corona688; 03-12-2013 at 03:43 PM..
# 11  
Old 03-12-2013
When I strtok, I put it in a for! Less magic, I guess! The positive test is more robust, as the world is just line feeds, numbers and not numbers.

I guess it might go awry with "- 1". Does *scanf() have more states to handle that? Can atof() deal with spaces after the sign? If you have them, check! The man says no: Man Page for strtod (all Section 3) - The UNIX and Linux Forums).
# 12  
Old 03-12-2013
Sorry to repeat. But it sounds like you DO create the data file. Is that correct?

If so, what if you simply change the data file to something like the following, and then the programming to read the data would be trivial, using fscanf.
Code:
varA   cnt     varB 
-21      1     0  
-21.2    4     3 4 5 6 
-21.4    5     45 65 87 98 98 
-22.0    5     345677 349887 98766 877654 987543 
-23.0    3     76549 8764 9873

# 13  
Old 03-12-2013
CSV might be nice, too -- just read with excel. However, differentiating numbers from not is pretty trivial. The major challenge here is the variable number of fields. A more normal form would have one varB per line, and downstream, assuming you do not lose the sort, you process when the two keys change or EOF. Normal could be put in RDBMS and processed in SQL. You are writing in two dimensions, sometimes across and sometimes down. But that's OK.
# 14  
Old 03-13-2013
Thx for this code Smilie

Quote:
Originally Posted by Corona688
Does this have to be C++? This would be trivial in many languages but annoying in C/C++.

Code:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
        char buf[1024];
        char buf2[1024];

        while(fgets(buf, 1024, stdin) != NULL)
        {
                char *tok;
                float x, y=0.0;
                int n=0;
                if(sscanf(buf, "%f %s", &x, buf2) != 2) continue;

                tok=strtok(buf2, ", \r\n\t");
                while(tok != NULL)
                {
                        float z;
                        n++;
                        if(sscanf(tok, "%f", &z) == 1) y+=z;
                        tok=strtok(NULL, ", \r\n\t");
                }

                printf("%f %f\n", x, y/n);
        }
}

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Reading columns using arrays

Hello, Please help in how to read rows and columns using array and print them. I have below output and i want to store this in array and print the required rows or columns. aaaaaaa 123 bbbbbb 456 ccccccc 888 Use code tags, thanks. (1 Reply)
Discussion started by: Cva2568
1 Replies

2. Shell Programming and Scripting

Removing carriage returns from multiple lines in multiple files of different number of columns

Hello Gurus, I have a multiple pipe separated files which have records going over multiple Lines. End of line separator is \n and records going over multiple lines have <CR> as separator. below is example from one file. 1|ABC DEF|100|10 2|PQ RS T|200|20 3| UVWXYZ|300|30 4| GHIJKL|400|40... (7 Replies)
Discussion started by: dJHa
7 Replies

3. Shell Programming and Scripting

How to split all columns into multiple columns?

Hi, all. How can I split all columns into multiple columns separated by tab? Input: qq ee TT 12 m1 aa gg GG 34 2u zz dd hh 56 4h ww cc JJ 78 5y ss ff kk 90 j8 xx pp mm 13 p0 Output: q q e e T T 1 2 m 1 a a g g G G 3 4 2 u z z d d h h 5 6 4 h w w c c J J 7 8 5 y (8 Replies)
Discussion started by: huiyee1
8 Replies

4. Shell Programming and Scripting

Reading multiple values from multiple lines and columns and setting them to unique variables.

Hello, I would like to ask for help with csh script. An example of an input in .txt file is below, the number of lines varies from file to file and I have 2 or 3 columns with values. I would like to read all the values (probably one by one) and set them to independent unique variables that... (7 Replies)
Discussion started by: FMMOLA
7 Replies

5. Shell Programming and Scripting

Compare multiple files with multiple number of columns

Hi, input file1 abcd 123 198 xyz1:0909090-0909091 ghij 234 999 xyz2:987654:987655 kilo 7890 7990 xyz3:12345-12357 prem 9 112 xyz5:97-1134 input file2 abcd 123 198 xyz1:0909090-0909091 -9.122 0 abed 88 98 xyz1:98989-090808 -1.234 1.345 ghij 234 999 xyz2:987654:987655 -10.87090909 5... (5 Replies)
Discussion started by: jacobs.smith
5 Replies

6. Shell Programming and Scripting

Awk match multiple columns in multiple lines in single file

Hi, Input 7488 7389 chr1.fa chr1.fa 3546 9887 chr5.fa chr9.fa 7387 7898 chrX.fa chr3.fa 7488 7389 chr21.fa chr3.fa 7488 7389 chr1.fa chr1.fa 3546 9887 chr9.fa chr5.fa 7898 7387 chrX.fa chr3.fa Desired Output 7488 7389 chr1.fa chr1.fa 2 3546 9887 chr5.fa chr9.fa 2... (2 Replies)
Discussion started by: jacobs.smith
2 Replies

7. Shell Programming and Scripting

Reading columns, making a new file using another as template

Hi fellas, I have two files such as: File 1 interacao,AspAsp,AspCys,CysAsp,CysCys,classe File 2 interacao,AspAsp,CysAsp,AspCys,CysCys,classe beta_alfa, DA, CA, DD, CD,ppi Thus, I want to make a File 3 using the File 1 as model: e.g. File 3... (2 Replies)
Discussion started by: valente
2 Replies

8. Web Development

mysql query for multiple columns from multiple tables in a DB

Say I have two tables like below.. status HId sName dName StartTime EndTime 1 E E 9:10 10:10 2 E F 9:15 10:15 3 G H 9:17 10:00 logic Id devName capacity free Line 1 E 123 34 1 2 E 345 ... (3 Replies)
Discussion started by: ilan
3 Replies

9. Shell Programming and Scripting

need help with post:extract multiple columns from multiple files

hello, I will would be grateful if anyone can help me reply to my post extract multiple cloumns from multiple files; skip rows and include filenames; awk Please see this thread. Thanks manishabh (0 Replies)
Discussion started by: manishabh
0 Replies

10. Shell Programming and Scripting

Reading columns in tab delimited file

I want to read only one column in "|" delimited file and write that column to a new file. For Ex: Input File 1|abc|324|tt 2|efd|11|cbcb 3||1|fg 4|ert|23|88 Output : I want to read column 3 in diff file. 324 11 1 88 Can anyone give me inputs on this ? (2 Replies)
Discussion started by: net
2 Replies
Login or Register to Ask a Question