LinuxQuestions.org
Visit Jeremy's Blog.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 07-21-2008, 12:19 PM   #1
frostpuppet
LQ Newbie
 
Registered: Jul 2008
Posts: 5

Rep: Reputation: 0
C++ I/O using a text file


here is my problem and i dont know C++ so i tried comming here to find help. What i need to do is take in a text file the first line as a 2d array breaking the two elements with a colon
the second line as a variable A
and the third line a variable B
and the 4th line a variable c the problem is that i dont know how to parse seperate lines like this is c++
the format of the text file is as follows

A:1 B:2 c:3
4
3
2


my code is as follows


// reading a text file
#include <iostream>
#include <fstream>
#include<iomanip>
//global declaration
using namespace std;


//Function to take in Alpahbet
int AlphabetIn (char alpha[40][40], int varA[01], int varB[01])
{

//Variables
int x, y=0, computer=0;

//Instructions
ifstream filein ("alphabet.txt");
if (filein.is_open())
{
//while file has not reached eof ( end of file built in)
while (! filein.eof() )
{
//get the first line of text THERE IS STILL A PROBLEM RIGHT HERE
filein.getline (alpha[y], 02, ':');
filein >> varA[y];
filein >> varB[y];
y++;
computer++;
}
//close file
filein.close();
}
else
//catch error in reading file since it did not open correctly
cout << "Ooops";
//output what was captured to determine where the error occured in reading in.
for (y=0; y<computer; y++)
{
for(x=0; x<30; x++)
{
cout<<alpha[y][x];
}
cout<<VarA[y] <<" " <<VarB[y];
}
cout<<"\n\n";
return Computer;
}


//MAIN
void main ()


{
//Variables
char alpha [80][30]={0};
int varA [02]={0};
int varB [02]={0};


//Instructions
AlphabetIn(alpha, VarA, VarB);
 
Old 07-21-2008, 12:33 PM   #2
matthewg42
Senior Member
 
Registered: Oct 2003
Location: UK
Distribution: Kubuntu 12.10 (using awesome wm though)
Posts: 3,530

Rep: Reputation: 65
Welcome to LQ.

Please post program code in [code] tags. This preserves whitespace and uses a fixed width font, which really helps people to read your post.

This really sounds like a homework problem. I will not provide you with working code (you would not learn anything by copy-pasting someone else code), but I am happy to guide you.

I do not really understand the description of the problem as you provided it. It would help to see what the input file looks like, and the expected output.
 
Old 07-21-2008, 01:12 PM   #3
kundor
Member
 
Registered: Aug 2003
Distribution: GoboLinux
Posts: 167

Rep: Reputation: 30
You don't want to loop, reading each element of the "array", and also try to read the last three lines each time. You want to loop, reading the multiple elements, and then after you're done with that, get the last three lines.

Why bother with one-element integer arrays? Just use pointers or references.

You have inner loops to go through your "2d" array, but what is supposed to be in this array? Your input file only has one line for this. I assume the array is supposed to look like this?

A B c
1 2 3

I am a little confused, because you made it 40x40, instead of 2x40.

Don't use leading 0s for literals (like 01, 02) unless you really mean the numbers to be octal.

You also have some capitalization errors in your variable names. Remember, C++ is case-sensitive.

I don't recommend messing with C arrays unless you need to. Since you have character values associated with numbers, apparently (A:1, B:2, c:3), why don't you use a map<string, int>? A map is an associative container, so for instance you could say map["A"] == 1, map["B"] == 2, and you can iterate through it and get the pairs of values.

So your declaration would look more like this
Code:
#include <string>
#include <map>

typedef map<string, int> simap;
int AlphabetIn (simap& alpha, int& varA, int& varB, int& varC) {
To loop over the first line, instead of trying to loop over the file and get an array element each time, try
while (filein.peek() != '\n' )

Then to put something in the map, this would work.
Code:
            string index;
            // Read label string, e.g. the A in A: (discards colon)
            getline(filein, index, ':');
            //Read integer after colon
            filein >> alpha[index];
Reading varA and so on goes after the loop.

To loop over the map, you can use an iterator, like this:
Code:
    for (simap::iterator it(alpha.begin()); it != alpha.end(); ++it) {
        cout << it->first << ": " << it->second << ", ";
    }
 
Old 07-21-2008, 01:23 PM   #4
frostpuppet
LQ Newbie
 
Registered: Jul 2008
Posts: 5

Original Poster
Rep: Reputation: 0
this is actually for my research so im not trying to learn c++ but were trying to run evaluations on certain algorithms. im not a coder and dont pretend to be as i am a math major. here is what it should do and i hope i can explain this better.

The text file is composed of 4 lines
the first line should be a letter followed by a colon then followed by a number for example A:1

this should be read in and then put into 2 corresponding arrays. the first array will contain the letter and the second array the number equivalent so that later a word such as cab can be converted to a number equivalent. in the case of CAB it would be equivalent to 312.

the second line of the text file is going to be a variable that i will store as A
the third line will be a variable stored as B
and the fourth line a variable stored as C

so a text file would look something like this

A:1 B:2 C:3
4
5
6

and a correct output would be

array 1 = ABC
array 2 = 123
A=4
B=5
C=6



I really appreciate all help anyone can give me i do again want to state that this is not a homework assignment for a class. The code that i posted earlier is what i could figure out based on come online tutorials. again i really appreciate the forum being as helpful as it is and helping out people that are new to this stuff.
 
Old 07-21-2008, 01:34 PM   #5
b0uncer
LQ Guru
 
Registered: Aug 2003
Distribution: CentOS, OS X
Posts: 5,131

Rep: Reputation: Disabled
First, even though a lot of examples do use the "using namespace std;" to shorten the written code a bit, do not use it in your programs. Even if you didn't use your own namespaces (which on the other hand may ease up your work), just learn it from the beginning -- it's easier later on that way -- that you specify the namespace you use every time you use something from the namespace. So:

Code:
// Not like this
using namespace std;
cout << "Using namespace feels good..";
But instead:
Code:
// This way you don't mess up things accidentally
std::cout << "A better way";
I know there are people who are hard against using std:: in front of every thing used from a namespace and rather tell you to use "using namespace..." if your app only uses the std namespace, but think about it this way: there is a reason why you can do std::cout instead of the other way, and when you learn something, it's a lot harder to forget-and-re-learn it the other way later than if you had thought about it in the first place.

Second thing (in addition to using code tags and saying it explicitly if this is a homework, to get proper answers and no angry posts): start off with simple things. If something doesn't work in your code or you don't get something fully, don't first write a 100+ or 1000+ lines long program and then start looking for errors -- instead isolate the problematic part into a program as small as possible, find a solution and then implement it into the big program you're creating. So if you have problems with file I/O, better write a very small program first that only reads a line (or writes) from (to) a file, and when it works without trouble, modify it so that it reads only certain part of the file, and when that works, so that it reads another piece of the file and so on. When you have the reading part working, put the thing into your big program and start working out next part.

And since C++ is object-oriented, consider if you're better off writing a main file with seven functions or if you're better off writing a class with some more general methods and then using that class. Even if it doesn't make sense in your current small program right now, you might well face a situation where you can re-use your class or it's methods. For example the file reading part; you could write a method that reads a given file in the way you need it to read it and returns the content (or parts of it) or stores them into an array or something, and when you've finished that method and made sure it works, you can simply include it into your program and use the method -- and focus on other things. Using just functions is C-style, and good in certain kinds of programs, but if you're really into C++ you're not getting everything out of it without considering the use of classes and their methods. If you find out you're writing similar code in more than one place, you might be easier off writing a general class, in some cases writing derived class(es) might help further. It depends on the program design really, but because C++ can do it, you should at least think about it.

Underlining the last sentence: think before writing. A lot of people can write, but a whole lot less is able to think enough to make sensible, usable, good code that is shorter and easier to write in the end. Well designed is half done.

EDIT: if it wasn't homework after all, sorry about that. There's just so many who try to feed their homework into the forums here hoping that somebody just gives them an answer without anybody needing to think or learn anything.

Last edited by b0uncer; 07-21-2008 at 01:36 PM.
 
Old 07-21-2008, 02:00 PM   #6
matthewg42
Senior Member
 
Registered: Oct 2003
Location: UK
Distribution: Kubuntu 12.10 (using awesome wm though)
Posts: 3,530

Rep: Reputation: 65
If you're a math-head, then C++ is going to cook your noodle because it is a total dogs dinner of a language. Not a lot of elegance in it, but it can be useful. ;-)

Is there a particular reason to use C++ and the STL container classes? I'm asking simply because this sort of processing is a lot more elegantly done with other languages.

It would simply things to split off parts of the problem into functions. One useful function would be to split a string into a vector of sub-strings based on some delimiter character. You could use that to split the whole of the first line into the three chunks, and also for each chunk into the bit before and after the colon.

A prototype of such a function might look like this:
Code:
vector<string> splitByDelimiter(const string& str, char delimiter);
The processing of the first line would then be much simplified.
 
Old 07-21-2008, 03:39 PM   #7
frostpuppet
LQ Newbie
 
Registered: Jul 2008
Posts: 5

Original Poster
Rep: Reputation: 0
to give more background about the project we are using c++ because a large portion of the project uses the NTL libraries. My job was to evaluate a few algorithms for affine map transformations if anyone is familiar with these. That is why im having such difficulty importing this text file since im not familiar with coding to being with. My job is really to evaluate a set of algorithms. While there is a c++ program already written for this because of the amount of algorithms i have to evaluate it is easier to write them out in text files than manually input everything every time. Thats why im allowed to come on here and use whatever code is given to me because this research project is not graded its for graduate case studies and the code is irrelevant. Part of the project that was given to me is done in c++ with an NTL library and even i dont know what that is. So the professor im working for is out of town and his e-mail he sent to me was just to check online because i should be able to change something to make it easier. He is the one telling me to go online and get something to get the outputs before he is back in town. If i couldnt figure it out before then he said ill just have to manually input everything. I hope this clarifies what im trying to do to anyone or gives a better understanding. Again i thank everyone for taking a look at this post.
 
Old 07-22-2008, 10:27 AM   #8
kundor
Member
 
Registered: Aug 2003
Distribution: GoboLinux
Posts: 167

Rep: Reputation: 30
Here, this code processes the file just fine (here, anyway.)

I don't know what you need to do with the data afterward, but from your description a map sounds fine.

Code:
#include <string>
#include <map>
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;
typedef map<string, int> simap;

int AlphabetIn (simap& alpha, int& varA, int& varB, int&  varC) {
    int y(0);
    ifstream filein ("alphabet.txt");

    if (filein.is_open()) {
        //while on first line
        while (filein.peek() != '\n' ) {
            string index;
            // Read label string, e.g. A in A: (discards colon)
            getline(filein, index, ':');
            //Read integer after colon
            filein >> alpha[index];
            ++y;
        }
        filein >> varA;
        filein >> varB;
        filein >> varC;
        filein.close();
    } else {
        //catch error in reading file since it did not open correctly
        cout << "Ooops";
    }
    //output what was captured to determine where the error occured in reading in.
    for (simap::iterator it(alpha.begin()); it != alpha.end(); ++it) {
        cout << it->first << ": " << it->second << ", ";
    }
    cout << '\n' << varA << '\n' << varB << '\n' << varC << '\n';

    return y;
}

int main () {
    simap alpha;
    int varA, varB, varC;
    AlphabetIn(alpha, varA, varB, varC);
    return 0;
}
 
Old 07-22-2008, 06:27 PM   #9
frostpuppet
LQ Newbie
 
Registered: Jul 2008
Posts: 5

Original Poster
Rep: Reputation: 0
thank you all for the feedback and help... Ive learned a little about c++ and everything has been working..
 
Old 07-24-2008, 12:47 PM   #10
frostpuppet
LQ Newbie
 
Registered: Jul 2008
Posts: 5

Original Poster
Rep: Reputation: 0
i hate to revive this but is there anyway to modify the above code to take in pairs of numbers

by that i mean similarly how A:1B:2 would map a to 1 and B to 2
could we take in 5:13 and and map the number 5 to the letter 13
 
Old 07-25-2008, 04:38 PM   #11
kundor
Member
 
Registered: Aug 2003
Distribution: GoboLinux
Posts: 167

Rep: Reputation: 30
Yes. Just change the map to a map<int, int>.

IE, (I am just listing the changed bits here)
Code:
typedef map<int, int> iimap;

int AlphabetIn (iimap& alpha, int& varA, int& varB, int&  varC) {
...
        while (filein.peek() != '\n' ) {
            int index;
            filein >> index;
            filein.ignore(256, ':'); //Ignores up to next colon, within 256 characters.
            filein >> alpha[index];
            ++y;
        }
...
The rest is the same, except for changing "simap" to "iimap" (and that's just an arbitrary name anyway, so you can leave them the same, or give it a better name.)

Also, the robustness against weird input (spaces or commas in the integers) is nonexistent. Feel free to extend.

Of course, the previous code also worked for pairs of numbers, it just stored the first number as text.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
How to parse text file to a set text column width and output to new text file? jsstevenson Programming 12 04-23-2008 02:36 PM
Steps needed to convert multiple text files into one master text file jamtech Programming 5 10-07-2007 11:24 PM
in Pascal: how to exec a program, discard text output or send to text file Valkyrie_of_valhalla Programming 6 05-02-2007 09:50 AM
how to change some text of a certain line of a text file with bash and *nix scripting alred Programming 6 07-10-2006 11:55 AM
How to find and change a specific text in a text file by using shell script Bassam Programming 1 07-18-2005 07:15 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 04:43 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration