473,322 Members | 1,510 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Assigning a portion of a getline to a variable

What is a good way to read a text file and read each line, then assign
data to variables? I have this so far,

#include <iostream>
#include <fstream>

using namespace std;

string BATCHNUMBER;
string BIS ="100";
string DEPARTMENT = "04";
string DESCRIPTION;
string DOCUMENTDATE;
string DOCUMENT;
string DUEDATE;
string FUND = "31Y";
string SCREEN = "31";

void main()
{
ifstream OpenFile;
OpenFile.open("youth.txt");
if(!OpenFile)
{
cout << "Error opening file! Aborting..." << endl;
exit(1);
}
else
cout << "File successfully opened..." << endl << endl;

cout << "Batch Number: ";
cin >> BATCHNUMBER;
cout << "Description: ";
cin >> DESCRIPTION;
cout << "Document Date: ";
cin >> DOCUMENTDATE;
cout << "Document: ";
cin >> DOCUMENT;
cout << "Due Date: ";
cin >> DUEDATE;

char line[50];
string vender[7];

while(!OpenFile.eof())
{
OpenFile.getline(line,50);
cout << line << endl;
}
OpenFile.close();
}

For example, if I want positions 1-7 to be assigned to a string
vender, then positions 10-12 to be assigned to a different string how
is that accomplished?

Here is a sample of the data file:

Y0TH004 210 100 50 5
Y0TH005 220 25 10 5
Y0TH008 200 50 60 55 1000

I have tested this and can read the file. After I get everything
loaded into variables, I will have to output to some other file to
format the data the way that is needed for an import to another
application.

Thanks for you help in advance.
Jul 22 '05 #1
2 3546

"Michael Easterly" <me*******@mchsi.com> wrote in message
news:54**************************@posting.google.c om...
What is a good way to read a text file and read each line, then assign
data to variables? I have this so far,

#include <iostream>
#include <fstream>

using namespace std;

string BATCHNUMBER;
string BIS ="100";
string DEPARTMENT = "04";
string DESCRIPTION;
string DOCUMENTDATE;
string DOCUMENT;
string DUEDATE;
string FUND = "31Y";
string SCREEN = "31";
Convention is to only use all upper case identifiers
for macros.

void main()
int main()
{
ifstream OpenFile;
OpenFile.open("youth.txt");
if(!OpenFile)
{
cout << "Error opening file! Aborting..." << endl;
exit(1);
IMO better would be:

return EXIT_FAILURE; /* needs #incluce <cstdlib> */
}
else
cout << "File successfully opened..." << endl << endl;

cout << "Batch Number: ";
cin >> BATCHNUMBER;
cout << "Description: ";
cin >> DESCRIPTION;
cout << "Document Date: ";
cin >> DOCUMENTDATE;
cout << "Document: ";
cin >> DOCUMENT;
cout << "Due Date: ";
cin >> DUEDATE;

char line[50];
string vender[7];

while(!OpenFile.eof())
eof() does not return true until *after* a failed read attempt.
{
OpenFile.getline(line,50);
cout << line << endl;
}
OpenFile.close();
The ifstream destructor will automatically close the
file for you. This statement is redundant (but harmless).
}

For example, if I want positions 1-7 to be assigned to a string
vender, then positions 10-12 to be assigned to a different string how
is that accomplished?

Here is a sample of the data file:

Y0TH004 210 100 50 5
Y0TH005 220 25 10 5
Y0TH008 200 50 60 55 1000
You can address specific positions in a std::string with its
[] operator, and you can get subsequences out of a std::string
with its 'substr()' member functions. BUT:
Your data does not appear to be column-aligned, but simply
separated by whitespace. So extracting particular columns
won't work.

I have tested this and can read the file. After I get everything
loaded into variables, I will have to output to some other file to
format the data the way that is needed for an import to another
application.

Thanks for you help in advance.


The following extracts each line as a 'record', stores each
whitespace-separated string into a 'field' of each record,
and outputs the data to cout (separating 'fields' with spaces,
and 'records' with newlines:
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <istream>
#include <ostream>
#include <sstream>
#include <string>

class Record
{
std::string line;
std::string batchnumber;
std::string description;
std::string documentdate;
std::string document;
std::string duedate;

friend std::istream& operator>>(std::istream& is, Record& r)
{
return is >> r.line
r.batchnumber
r.description
r.documentdate
r.document
r.duedate;

}

friend std::ostream& operator<<(std::ostream& os, const Record& r)
{
return os << r.line << ' '
<< r.batchnumber << ' '
<< r.description << ' '
<< r.documentdate << ' '
<< r.document << ' '
<< r.duedate;
}
};

const int status[] = {EXIT_SUCCESS, EXIT_FAILURE};

int main()
{
std::string filename("data.txt");
std::ifstream input(filename.c_str());
bool err(!input);

if(!err)
{
std::string line;

while(std::getline(input, line))
{
std::istringstream iss(line);
Record rec;
iss >> rec;
std::cout << rec << '\n';
}

if(err = (!input && !input.eof()))
cerr << "Error reading file '" << filename << "'\n";
}
else
cerr << "Cannot open file '" << filename << "'\n";

return status[err];
}

-Mike
Jul 22 '05 #2
On 28 May 2004 11:20:27 -0700 in comp.lang.c++, me*******@mchsi.com
(Michael Easterly) wrote,
What is a good way to read a text file and read each line, then assign
data to variables?
There is no single answer to that, it depends on many things such as how
complex your data format is, and what kind of error recovery you
require. But,
while(!OpenFile.eof())
{
that isn't part of it. Don't loop on eof(), instead read until reading
fails. Then check eof() to see if that was the reason, if you still
care.

std::string line;
while(std::getline(openfile, line)
{
For example, if I want positions 1-7 to be assigned to a string
vender, then positions 10-12 to be assigned to a different string how
is that accomplished?

Here is a sample of the data file:

Y0TH004 210 100 50 5


OK, your fields appear to be delimited by whitespace. That makes things
easy, since that's the default behavior for stream formatting
operator>>(). You could do something like:

while(std::getline(openfile, line)
{
std::istringstream parse(line);
parse >> f1 >> f2 >> f3 >> f4;
if(parse.good())
// do something with the data.
}

For more complicated input format, one of the first things I think of
these days is the regex library from http://www.boost.org

Jul 22 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: vanGogh | last post by:
I have generated classes based on an Xml schema file (xsd) using the XSD.exe tool. My goal is to: - write an application that can parse XML documents - fill objects (based on the generated...
6
by: Alex | last post by:
here is the code i am having trouble with. // first, I have a global variable char *sName; .... ..... // and then this function void set_characterNameAgeSex() { char setName; char *sTransfer;
10
by: Skywise | last post by:
I keep getting the following error upon compiling: c:\c++ files\programs\stellardebug\unitcode.h(677) : error C2664: 'class istream &__thiscall istream::getline(char *,int,char)' : cannot convert...
3
by: algorithm | last post by:
Hi, I've a simplified program snippet in which getline behaves in a way, which at least I find odd: // File: getline_example.cpp #include <iostream> #include <string> using namespace std;
14
by: KL | last post by:
I am so lost. I am in a college course for C++, and first off let me state I am not asking for anyone to do my assignment, just clarification on what I seem to not be able to comprehend. I have a...
3
by: mamun | last post by:
Hi all, I am trying to create variables dynamically. This is needed because the user interface can have ten different textboxes with name as txt1, txt2 and so on. I would like to get values of...
13
by: theronnightstar | last post by:
I seem to be having a problem with getline(). I have tried to find it on google, but I'm not seeing the answer. The goal of this section of code is simply to read in a line from a file to a...
6
by: bryant058 | last post by:
#include<iostream> #include<cstring> #include<string> #include<iomanip> using namespace std; int main() { string s; char *tokenptr; int space;
8
by: sabby | last post by:
I want to use the getline() so that i can enter a entire name in on line. (with spaces) The prob is that i am initializing the variable as "N/A" and saving it to a text file. it is declared as a...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.