473,587 Members | 2,229 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 << "Descriptio n: ";
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.getlin e(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 3564

"Michael Easterly" <me*******@mchs i.com> wrote in message
news:54******** *************** ***@posting.goo gle.com...
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 << "Descriptio n: ";
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.getlin e(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::getl ine(input, line))
{
std::istringstr eam 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::getl ine(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::getl ine(openfile, line)
{
std::istringstr eam 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
1587
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 classes) with the XML data in element nodes or attributes - assemble the objects so they are contained in their parent - add the resulting object to an...
6
439
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
5599
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 parameter 1 from 'const char *' to 'char *' Conversion loses qualifiers I have a data file called Standard.udf The Data File (not the problem):...
3
1593
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
3869
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 ..txt file that I want to read into a multi-dimensional string array. Each line of the file needs to be read into the array. OK..sounds easy...
3
1802
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 all and then run in single transaction. for (int i = 1; i <= 10; i++) { (qry + i)= "insert into table1(field1) values(value1)";
13
2296
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 string according to the conditions of the do...while statement. /////code void populate( vector<string>& unplayed_anagrams, string& word, const
6
2374
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
2856
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 string. look at the code: #include <iostream.h> #include <fstream> #include <cstdlib> #include <string> using namespace std; //Account data...
0
7843
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8339
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7967
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8220
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6619
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5712
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5392
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3872
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1452
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.