Archived

This topic is now archived and is closed to further replies.

iostream question... (probably simple)

This topic is 5889 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Lets suppose I want to use the iostream functions to load in a regular .txt file, that looks something like this:
  
hi 42
1.03937 foo
I like cheese.
  
Now lets suppose I Just want to read the numbers only. Would this work, or would it read in the characters as numbers?
  
#include "iostream.h"

//...program stuff goes here...


fstream fin("thing.txt");
int NumberOne = 0;
float NumberTwo = 0.0f;
char Cheesy[256];

fin<<NumberOne;
fin<<NumberTwo;
fin<<Cheesy;
  
What would NumberOne, NumberTwo and Cheesy contain? I am basically looking for a way to read in numbers that are embedded in the text, and read the text if I need to that is after some numbers. Anyone?

Share this post


Link to post
Share on other sites
Well, I suppose I am a bit lazy and that I have a distinct fear of compiling errors. Go ahead and call me a chicken. That and I thought someon might know the answer.

Share this post


Link to post
Share on other sites
I hacked together a program real quick and it turns out it won''t work. My program was like so:
  
#include <iostream.h>
#include <fstream.h>

int main()
{
char stringy;
int testnum = 9;
ifstream in("test");

cout<<"trying to read a number\n";
in>>testnum;
cout<<testnum<<endl;

cout<<"trying to read a string\n";
in>>stringy;
cout<<stringy<<endl;


return 0;

}

And the contents of the file was:
  
one 1 two 2

It gave me 9 as the first number it printed out and it printed out a funny character as the second. Its too bad fstream couldn''t automatically find the next character(s) of the specified type and read them in... Rather interesting little experiment if I must say.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Okies: using my l33t BCB Skills, I have made a working function for _your_ text:

  
#include <fstream.h>
ifstream in("thing.txt");
int i1;
float f1;
String parse;
char words[256];
char extras[10];
in.getline(words,255);
extras[0] = words[3];
extras[1] = words[4];
extras[3] = 0;
parse = extras;
i1 = parse.ToInt();
in.getline(words,255);
for (int i = 0; i<7; i++)
{
extras[i] = words[i];
}
extras[7] = 0;
parse = extras;
f1 = parse.ToDouble();
in.getline(words,255);
in.close();


This is evidently convoluted, and should you have written it as:
  
hi
42
1.03937
foo
I like cheese.

it could be processed as:

  
#include <fstream.h>
ifstream in("thing.txt");
int i1;
float f1;
String l1,l2,l3;
char words[256];
in.getline(words,255);
l1 = words;
in >> i1 >> f1;
in.getline(words,255);
l2 = words;
in.getline(words,255);
l3 = words;
in.close();

Share this post


Link to post
Share on other sites