Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C++ input problems

Status
Not open for further replies.

s0hel

Programmer
Jul 15, 2004
8
0
0
US

I have a program that needs to read in an unknown number of characters

for example, the input can be:

---
AC 0
DC 50
START 1
CPU 30
END
START 102
CPU 40
END

---

I will need to do some processing based on that input, but there can any number of 'START's and 'END's

the way my program will executed is this way:

program1 < data.txt

data.txt can have any number of characers in there, i need to find a way to store all the data -- does anyone know a method for checking that? checking if there is nothing in the buffer maybe?

thanks..

-Sohel
 
Just use an ifstream object's getline() method in conjunction with a while loop to read the file line by line, you shouldn't have too much difficulty.
 
But what if it's just one incredibly long line? :)

I believe the ifstream::getline() takes a char*, so you'd need to allocate enough space...

Looking at other getline(), I think that should work since it takes an ifstream and string parameters. Here's the sample program in the MSDN:
Code:
#pragma warning(disable:4786)
#include <string>
#include <iostream>

using namespace std ;

void main()
{
    string s1;
    cout << "Enter a sentence (use <space> as the delimiter):";
    getline(cin,s1, ' ');
    cout << "You entered: " << s1;
}
 
you may also want to consider some of the logical parsing...like, is there going to be an "end" for every "start"? what are the datatypes of the individual components (string, int, double, etc...)? Is there a Max/Min length for the different components? Is there a logical setup for what a record will contain (ie. can you create a class/struct to hold the respective components)? Will there always be space delimiting the components? Then you may consider reading character by character and looking for delimiting characters and keywords (ie "start", "end", " ", "\t" etc...). Further you may want to use the .peek method...all this considered, just read till the eof, and you'll be all right, just parsing certain parts.

If you can answer these questions, you're halfway there.

Good luck,
Kevin

- "The truth hurts, maybe not as much as jumping on a bicycle with no seat, but it hurts.
 
all i needed to do was this:

char input[8192];

fread(input, 8192, stdin);

that worked fine.

or to get it line by line

char input[128];

do
{
fgets(input, 128, stdin);
} while (input[0] != 0);

thats it!

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top