I have a .txt file which I'm trying to gather data from, that can then be used within variables within my code to be used in other functions.
Here's an example of my text file:
0 10 a namez 1 0
0 11 b namea 1 1
1 12 c nameb 1 1
2 13 d namec 0 1
3 14 e named 1 1
So my file will not always be the same number of lines, but always the same number of variables per line.
I currently have this, to firstly get the length of the file and then change the amount of rows within the array:
int FileLength()
{
int linecount = 0;
string line;
ifstream WorkingFile("file.txt");
while(getline(WorkingFile, line))
{
++linecount;
}
return linecount;
}
int main()
{
string FileTable [FileLength()][6];
}
Firstly I don't know if the above code is correct or how I can add the values from my file into my FileTable array.
Once I have my FileTable array with all the file data in it, I then want to be able to use this in other functions.
I've been able to do:
if(FileTable[2][0] = 1)
{
cout << "The third name is: " << FileTable[2][3] << endl;
}
I understand my code may not make sense here but I hope it demonstrates what I'm attempting to do.
I have to do this for a larger text file and all the 6 variables per line relate to be input to a function.
Hold each line in its own object, this is much clearer:
struct Entry
{
std::array<std::string, 6> items; // or a vector
};
In main:
std::vector<Entry> file_table( FileLength() );
Note that it is a waste of time to read the whole file first in order to find the number of entries. You could just start with an empty vector, and push in each entry as you read it.
Your access code:
if( file_table.size() > 2 && file_table[2].items[0] == "1" )
{
cout << "The third name is: " << FileTable[2].items[2] << endl;
}
I would actually recommend giving the members of Entry names, instead of just having an array of 6 of them. That would make your code more readable. (Unless you really need to iterate over them, in which case you can use an enum for the indices).
You could define an operator[] overload for Entry if you don't like the .items bit.
since the number of lines is dynamic I suggest to use vector instead of array. you can push back your data to the vector line by line until you read eof.
also try to study about OOP a little , it would make your code more understandable.
take look at these:
http://www.cplusplus.com/reference/vector/vector/
http://www.geeksforgeeks.org/eof-and-feof-in-c/
Related
I'm trying to save numbers from first txt file to second one in reversed order.
To be clear, inside 1st txt I have typed numbers from 1 to 10 (decimal notation). When I try to count them, I get 5 or 7, depending on what's between them (space or enter).
Then, another error is that inside 2nd txt program saves as much "0s" as dl's variable value is equal to instead of loaded numbers in reversed order.
I paste the whole code, because I don't know file operation rules good enough to determine which exact part could be the source of problem. Thank You in advance.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
fstream plik1;
plik1.open("L8_F3_Z2a.txt", ios::in | ios::binary);
fstream plik2;
plik2.open("L8_F3_Z2b.txt", ios::out);
if(!plik1.good() || !plik2.good()) {
cout << "file(s) invalid" << endl;
return 1;
}
plik1.seekg(0, ios::end);
int dl = plik1.tellg() / sizeof(int);
cout << "length = " << dl << endl;
int a;
for(int i = 0; i < dl; i++) {
plik1.seekg((i + 1) * sizeof(int), ios::end);
plik1 >> a;
plik2 << a;
cout << i + 1 << ". a = " << a << endl;
}
plik1.close();
plik2.close();
return 0;
}
edit the output is:
length = 7
1. a = 0
2. a = 0
3. a = 0
4. a = 0
5. a = 0
6. a = 0
7. a = 0
--------------------------------
Process exited after 0.03841 seconds with return value 0
Press any key to continue . . .
Problem
When a file is encoded as text the binary size of the data is irrelevant.
int dl = plik1.tellg() / sizeof(int);
will get you the side of the file in integers, but the file isn't storing integers. It is storing a stream of characters. Say for example the file holds one number:
12345
which is five characters long. Assuming the file is using good ol ASCII, that's 5 bytes. When 12345 is converted to an int it will probably be 4 or 8 bytes and almost certainly not 5 bytes. Assuming the common 32 bit (4 byte) int
int dl = plik1.tellg() / sizeof(int);
int dl = 5 / 4;
int dl = 1;
Yay! It worked! But only by the grace of whatever deity or cosmic entity you worship. Or don't worship. I'm not going to judge. To show why you can't count on this, lets look at
123
this is three characters and 3 bytes, so
int dl = plik1.tellg() / sizeof(int);
int dl = 3 / 4;
int dl = 0;
Whoops.
Similarly
1 2 3 4 5
is five numbers. The file length will probably be the sum of one byte per digit and one byte per space, 9 bytes.
Where this gets weird is some systems, looking at you Windows, use a two character end of line marker, carriage return and a line feed. This means
1
2
3
4
5
will sum up to 13 bytes.
This is why you see a different size depending on whether the numbers are separated with spaces or newlines.
Solution
The only way to find out how many numbers are in the file is to read the file, convert the contents to numbers, and count the numbers as you find them.
How to do that:
int num;
int count = 0;
while (plik1 >> num) // read numbers until we can't read any more
{
count++;
}
From this you can determine the size of the array you need. Then you rewind the file, seek back to the beginning, allocate the array and read the file AGAIN into the array. This is dumb. File IO is painfully slow. You don't want to do it twice. You want to read the file once and store as you go without caring how many numbers are in the file.
Fortunately there are a number of tools built into C++ that do exactly that. I like std::vector
std::vector<int> nums;
int num;
while (plik1 >> num)
{
nums.push_back(num);
}
vector even keeps count for you.
Next you could
std::reverse(nums.begin(), nums.end());
and write the result back out.
for (int num: nums)
{
plik2 << num << ' ';
}
Documentation for std::reverse
If your instructor has a no vector policy, and unfortunately many do, your best bet is to write your own simple version of vector. There are many examples of how to do this already on Stack Overflow.
Addendum
In binary 5 integers will likely be 20 or 40 bytes no matter how many digits are used and no separators are required.
It sounds like storing data as binary is the bees knees, right? Like it's going to be much easier.
But it's not. Different computers and different compilers use different sizes for integers. All you are guaranteed is an int is at least 2 bytes and no larger than a long. All of the integer types could be exactly the same size at 64 bits. Blah. Worse, not all computers store integers in the same order. Because it's easier to do some operations if the number is stored backwards, guess what? Often the number is stored backwards. You have to be very, very careful with binary data and establish a data protocol (search term for more on this topic: Serialization) that defines the how the data is to be interpreted by everyone.
I'm working on a card game in C++ where I want to get some user input via getline(). The input needs to be in this specific format:
"1 2 3 4 5 6"
The range of numbers is 1-11 and each number must be seperated with a space. The user is putting in index numbers for a vector. Say he writes "1 2 3" and hits enter, position 0, 1 and 2 are being adressed by the vector.
I'm also open for any other recommendations considering the design decision to let the user input the vector (or essentially their card's) position.
The player cards are displayed in this format "1 blue" and are stored as strings in a vector. I figured it is too much hassle for the user to input the whole card name, so I chose to use the vector index.
Below is the code snippet of my regex string. It works, kinda. It just pushes the whole string in the vector, missing the 10. But I don't need 1 vector element like this: "1 2 3 4", I need 4 vector elements with every number being one element.
Things that shouldn't match:
"1234567"
"abcdef"
"12 34 567 32"
If you need any further context, I will gladly provide so.
Thanks in advance
int main()
{
int i = 0;
std::regex rx("([[:digit:]]\\s)+([[:digit:]]\\s)+");
std::string line = "1 2 3 4 5 6 7 8 9 10";
std::smatch m;
std::vector<std::string> catchit;
while (regex_search(line, m, rx))
{
std::cout << "Pattern found " << m[i] << '\n';
catchit.push_back(m[i]);
line = m.suffix().str();
i++;
}
return 0;
}
This solves my problem without having to use regex, thank you very much #Nick
Why not std::cin? Or wrap your output from getline in a
std::stringstream and use operator>> to read numbers one at a time and
validate them then? E.g. std::stringstream stream(line); /* loop */
stream >> val; if (val < 0 || val > 11)...
I am trying to open a text file and pass the lines of the text file to a vector. The first digit in each line is the size of the vector and since I do not know the end point of the text file I am using a while loop to find the end. The idea is that I can take a text file and run a merge sort on it. So, for example:
3 5 4 9
5 0 2 6 8 1
sorted it would be become:
4 5 9
0 1 2 6 8
The problem I am having is that when I sort a vector that is larger than the prior vector (as in the example) I do not get output. It is probably something simple that I just have over looked. I am pretty sure the issue is in the code below. Thanks for any pointers.
while (!file.eof())
{
int size;
file >> size;
vector<int> myVector(size);
int n = 0;
while (n < size && file >> myVector[n])
{
++n;
}
sort(myVector);
for (int j = 0; j < size; ++j)
{
if (file.eof()) break;
cout << myVector[j] << ' ';
}
cout << '\n';
}
The problem is this line:
if (file.eof()) break;
Once you've read the last line of the file, file.eof() will be true. So the first time through the loop that's supposed to print the sorted vector, you break out of the loop and don't print anything. It has nothing do with whether the vector is larger than the previous vector, it's just a problem with the last line of the file. The fix is to get rid of that unnecessary line.
You also need to change the main loop. while (!file.eof()) is the wrong way to loop over a file's contents (see the linked questions for full explanations). Use:
int size;
while (file >> size) {
...
}
because of the line :
if(file.eof()) break;
if you get to eof your program wont print anything since you break the printing loop on its first iteration
for instance - if there are no chars after 8 in your example - you wont get output ,but even a single space can change that
besides that - is there any chance or cases that your sorting function clears a vector ? or changes it ?
So I have a file that has multiple columns of data like this:
1 2 3
4 5 6
7 8 9
etc...
And I'm traversing through this file with a while loop trying to store the data in a vector as I go along. But when I use a delimiter to deal with the spaces in between the data it only reads the first line and stops. The code for the while loop is as follows:
while(getline(infile,content, ' '))
{
double temp = atof(content.c_str();
cout << "value storing is: " << temp << endl;
data.push_back(temp);
}
Using the data above with this code I just get "1 2 3" as the output. So i'm not sure where I'm going wrong with this.
The column the numbers are in are also important when I crunch the data later. For example, every iteration of the while loop will add a counter and every time it goes to a new line will be another counter so with that i can figure out how many lines I have so when I need to compute something I can use i%(columnNumber) to grab that value.
Thanks for any light anyone can shed on my situation.
It's because there are no spaces after a new line.
This is what the file looks like (to std::getline())
1 space 2 space 3 newline 4 space 5 space 6 newline 7 space 8 space 9
I can't reproduce "1 2 3" as output. When I run your code, I get
value storing is: 1
value storing is: 2
value storing is: 3
value storing is: 5
value storing is: 6
value storing is: 8
value storing is: 9
where my test file looks like this:
1 2 3
4 5 6
7 8 9
To fix the problem, try doing something like this:
int main()
{
std::ifstream in("test");
std::string content;
std::vector<int> data;
while (getline(in, content))
{
std::stringstream linestream(content);
int value;
// Read an integer at a time from the line
while(linestream >> value)
{
// Add the integers from a line to a 1D array (vector)
data.push_back(value);
std::cout << "value storing is: " << value << std::endl;
}
}
}
Just need general project help.
Basically I need to do this for 8 players. The numbers come from a file im supposed to call in. The first 5 numbers for for the first 5 games, the next for rebounds, and then for blocks. Im assuming I need to call in a loop to read the first name, last name, points, rebounds and blocks, process that info and then output the information.Any tips/ suggestions?
ex from the text file:
Thomas Robinson 17 28 10 16 10 11 12 13 8 9 1 1 1 0 1
ex from what I'm supposed to return that information to
Game Log
-----------------------------------------------------------------------------
Player Name : Thomas Robinson
-----------------------------------------------------------------------------
Game # Points Rebounds Blocks
-----------------------------------------------------------------------------
1 17 11 1
2 28 12 1
3 10 13 1
4 16 8 0
5 10 9 1
-----------------------------------------------------------------------------
I think this is homework, but since I don't know which functions can be used, and which functions can't, my answers may be can't fit the request.
At a first look, I got three ideas.
1) using ifstream::get()
ifstream in_file;
in_file.open("your_file_name.txt");
char ch;
string str = "";
while(in_file.get() != '\n')
{
str = "";
while((ch = in_file.get()) != ' ')
{
// add ch to str.
str += string(&ch, 1);
}
// push str into an array, vector, stack, etc.
/*...*/
}
in_file.close();
2) read the line into a string, and then use a split function, you can find how to implement a split function everywhere.
3) use the ifstream::getline() function, it provides a delemiter parameter.
you can find the usage of ifstream::get() and ifstream::getline() here and here
The code I provide in 1) is probably not a good practice, you should check the 'EOF' stream error, in_file.open()'s exceptions etc.
btw, the code I first wrote was an error code, you can't use str += string(ch), you should either write str += string(&ch, 1) or str += string(1, ch) or str += ch you can find string's constructors here. Sorry for the error code again.
You can parse the file with the ">>" operator pretty nicely if everything is separated by spaces and newlines. Which is how the ">>" operator works. So, yes, you need a loop. Basically you want the loop to work like this:
(I never knew you could do this in Comp Sci 1. It would've saved me so much trouble...I used to do things like what the other answer is doing.)
(I'm also assuming you know how to open a txt file as an ifstream. If not, see http://www.cplusplus.com/reference/iostream/ifstream/open/.)
int temp;
int n = 0;
int x = 1;
while(textfile >> temp) // Each time through the loop, this will make temp
// the next value in the file. It will stop when
// there's nothing more to read.
{
/* Now it's going to go from left to right through the file, so you
need some logic to put it in the right place. you know that every
five numbers start a new column, so:*/
array[x][n] = temp; //Start x at 1 because you're skipping the first column
n++;
if (n == 5) {
n = 0;
x++; //Every five values, move on to the next column
}
Now your array will have the stuff where it needs to be. Just output it according to plan.