By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,305 Members | 1,619 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,305 IT Pros & Developers. It's quick & easy.

getline and C

P: 6

I am new at computer programming and I am having trouble using getline() in C.
I use an input file that contains 12 variables on every line.
From the printf statements below, I notice that scanf, although risky, does the job correctly.

However, getline skips the first line from the input file and evaluates the last line twice.
Do you have any idea what I am doing wrong?

Thank you for your comments!

#include <stdio.h>

float aa,ab,ac,ba,bb,bc,ca,cb,cc,da,db,dc;
struct point {
float x;
float y;
float z;
char *memal;
int nbytes = 1000;


while (getline(&memal, &nbytes, stdin) != -1)
scanf("%6f %7f %7f %7f %7f %7f %7f %7f %7f %7f %7f %7f", &ca, &cb, &cc, &aa, &ab, &ac, &da, &db, &dc, &ba, &bb, &bc);

struct point ptx0 = {aa, ab, ac};
struct point ptx1 = {ba, bb, bc};
struct point ptx2 = {ca, cb, cc};
struct point ptx3 = {da, db, dc};

printf("%f\n", ptx2.x);
printf("%f\n", ptx2.y);
printf("%f\n", ptx2.z);
printf("%f\n", ptx1.z);

Mar 21 '07 #1
Share this Question
Share on Google+
2 Replies

Expert 100+
P: 1,510
the getline() will skip every other line. If all lines contain 12 values just check the conversion works OK, e.g.
Expand|Select|Wrap|Line Numbers
  1. while (scanf("%6f %7f %7f %7f %7f %7f %7f %7f %7f %7f %7f %7f", 
  2.     &ca, &cb, &cc, &aa, &ab, &ac, &da, &db, &dc, &ba, &bb, &bc)==12)
  3. {
  4.   // 12 values read ..
  5. ...
  6. }
  7. // read failed
Mar 21 '07 #2

P: 6
Thank you for your comment!

I did what you indicated, replacing the getline function using scanf as a test.
Now it sometimes skips lines in the middle of the input file as well, even though they all contain 12 variables. However, the last line is only evaluated once.
The input file is actually the result of an other program that puts these 12 variables on a line, followed in the end by \n, so I guess there should be no difference between these lines.

Here's part of the program where the input file is being created.

for (i=0; i< imax; i++)
if (num == (2+i*7)){
struct bead bdeth = {xx, yy, zz};
printf("%6.3f %6.3f %6.3f ", bdeth.x, bdeth.y, bdeth.z);
else if (num == (3+i*7)){
struct bead bdori = {xx, yy, zz};
printf("%6.3f %6.3f %6.3f ", bdori.x, bdori.y, bdori.z);
else if (num == (4+i*7)){
struct bead bdpro = {xx, yy, zz};
printf("%6.3f %6.3f %6.3f ", bdpro.x, bdpro.y, bdpro.z);
else if (num == (7+i*7)){
struct bead bdmet = {xx, yy, zz};
printf("%6.3f %6.3f %6.3f\n", bdmet.x, bdmet.y, bdmet.z);
Mar 21 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.