How to move file pointer back by one integer? - c++

Say I have a file containing integers in the form
1 57 97 100 27 86 ...
Say that I have a input file stream fin and I try to read the integers from the file.
ifstream fin("test.txt");
int val;
fin>>val;
Now I am doing this action in a while loop where at one period of time, I want to move my file pointer exactly one integer back. That is if my file pointer is about to read the integer 27 when I do fin>>val, I want to move the file pointer such that it can read the integer 100 when I do fin>>val. I know we can use fin.seekg() but I have used it only to move the file pointers by characters, not by integers.
Probably this is a naive question. But can someone please help me out?

You can use tellg after each read to save the pointer to be used later on with a seekg.
You could also take the implementation of << and modify it with a function that also returns the number of characters you have advanced each time. Where to find the source code of operator<< is not something where I could easily help you with.

In your case it is not an integer, but a text representing a number. Because of this you will have to move backward character by character until you find a non-digit one (!isdigit(c)).
As one of the commenters below pointed out, you may also pay attention to a the 'minus' sign in case your numbers can be negative.

first argument is the file name, second argument is the numbers index, program displays the number at the index and then displays the previous number (counting from zero)
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
int main(int argc, char *argv[]){
if(argc != 3){
std::cout<<"argument error!\n";
return 1;
}
std::ifstream read;
read.open(argv[1],std::ios::app);
if( read.is_open() ){
std::vector<int> numbers;
int temp;
while(read >> temp){
numbers.push_back(temp);
}
std::cout<<"1) "<<numbers[atoi(argv[2])]<<"\n2) "<<numbers[atoi(argv[2]-1)]<<std::endl;
read.close();
}else {
std::cout<<"file open error!\n";
return 2;
}
return 0;
}

Try the following:
#include <iostream>
#include <fstream>
#include <locale>
int main()
{
std::ifstream fin("test.txt");
int val;
bool back = false;
for (int i = 0; fin >> val;)
{
if (!back && val == 27)
{
while (i++ < 2)
while (!std::isspace(fin.unget().rdbuf()->sgetc()));
back = true;
}
}
}

You could take a look at istream::unget()

#include <fstream>
#include <iostream>
int main()
{
ifstrem file("fileName.txt");
char var=file.get()://now this will move file pointer one time forward
/* Seekg(n,position) accept two arguments.The number of bits and position
from where to move the file pointer
if value of n is negative then file pointer will move back.
*/
file.seekg(-1,ios::cur);//to move the file back by one bit from current position
retur
n 0;
}

Related

C++ twoSum. Optimize memory usage

I am solving a twoSum problem.
Steps:
Read an input file with a following template:
7
1 7 3 4 7 9
First line is the target number, second line is a number sequence.
Numbers can be in range 0 < N < 999999999
If the sum of two numbers from the number sequence equals the target number, I write "1" to the output file.
If there are no numbers the sum of which equals the target number then I write "0" to the output file.
I need to optimize memory usage in my code. How can I do that?
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <string>
#include <algorithm>
using namespace std;
int main() {
ifstream f1;
vector<int> nums;
string line;
string source;
//Open input file and read it to a string
f1.open("input.txt");
while (getline(f1, line, '\n')) {
source+=line + " ";
} f1.close();
//Parse the string into an int vector
stringstream parser(source);
int num;
while (parser >> num) { nums.push_back(num); }
//Clear used strings
line = "";
source = "";
//Get target number
int target = nums.at(0);
//Get number sequence
nums.erase(nums.begin());
bool flag = false;
//Check number sequence for two numbers sum of which equals the target number
unordered_map<int, int> mp;
for(int i=0;i<nums.size();i++){
if(mp.count(nums[i])==1){
flag = true;
break;}
mp[target-nums[i]]=i;
}
//Write the result into the output file
ofstream f2;
f2.open("output.txt");
f2 << flag;
f2.close();
}
There are a couple of things you can do to minimise memory usage here. First up, you don't need to read entire contents of the file into std::string. You can read directly into std::vector, or better still read the file contents into a single int variable and process the numbers as you go. Another thing: you do not need to use a std::unordered_map, because presence of the key is the only thing you are really interested in, so std::unordered_set is sufficient. Below a simple solution making use of that suggestions:
#include <fstream>
#include <unordered_set>
int main() {
std::ifstream input {"input.txt"};
int target;
input >> target;
int current_number;
bool found = false;
std::unordered_set<int> observed_numbers;
while (input >> current_number) {
if (observed_numbers.count(target - current_number) > 0) {
found = true;
break;
}
observed_numbers.insert(current_number);
}
std::ofstream output {"output.txt"};
output << found;
}

Atoi function while reading a .csv file C++

The execution of my code crashes when it gets to the "atoi" function, but I cannot understand why.
The code is supposed to read a matrix from a .csv file, considering:
- the first row (so till the first '\n') and saving each element (separated by a ',') in a vector of ints; - the rest of the matrix, by looking at each element and creating a specific object if the number read is 1 or 2.
I don't get any exception while debugging the program, it just crashes during the execution (and using the system ("PAUSE") I could figure out it was the atoi function which didn't work properly).
Can you help me understand what is going wrong?
Thank you very much.
Ps: I also attached all the libraries I'm loading... maybe it can help :)
#include <fstream>
#include <stdio.h>
#include <sstream>
#define nullptr 0
#include <string>
#include "classi.h"
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
ifstream file("problem.csv");
unsigned int N = 0;
unsigned int M = 0;
char c; //modificato char * c;
unsigned int i=0,j=0, k=0, n_iter, j_temp =0;
std::vector<car> v_row;
std::vector<car> v_col_temp;
std::vector<int> iter; // location where I want to save the ints corresponding to the elements of the first row of the .csv file //
std::string iterazioni; //location where I want to save the first row as a string and then cut it into pieces (iteraz) and then convert (atoi --> iter)
std::string iteraz;
while(!file.eof()){
std::getline(file,iterazioni,'\n');
stringstream it(iterazioni);
while (it.good()) {
std::getline(it,iteraz, ',');
iter[k] = atoi(iteraz.c_str());
if(iter[k]<0){
cout<<"Errore: negative #of iterations"<<endl;
break;
}
iter.push_back(0);
k++;
}
iter.pop_back();
file.get(c);
if (c=='1'){
blue_car b(i,j);
if (v_col_temp[i].get_next() != nullptr)
v_col_temp[i].insert_tail(&b);
else
v_col_temp[i].insert_head(&b);
}
if (c=='2'){
red_car r(i,j);
if (v_row[i].get_next() != nullptr)
v_row[i].insert_tail(&r);
else
v_row[i].insert_head(&r);
}
if (c==',') {
j++;
if (i == 0)
j_temp++;
}
if (c=='\n'){
car p;
v_row.push_back(p);
v_col_temp.push_back(p);
i++;
if (j != j_temp) {
std ::cout<<"errore input non valido: numero righe/colonne non coerente"<<endl;
}
j=0;
}
else if ((c!='\n') && (c!=',') && (c!='0') && (c!='1') && (c!='2'))
std ::cout<<"errore input non valido"<<endl;
};
n_iter = k-1;
M=i;
N=j+1;
...
Your program crashes because you failed to initialize the contents of the iter vector.
std::vector<int> iter; // location where I want to save the ints corresponding to the elements of the first row of the .csv file //
You declare and construct this vector. The vector is empty at this point, and it has no elements.
At some point later:
iter[k] = atoi(iteraz.c_str());
The initial value of k is 0, so this attempts to assign the return value from atoi() to iter[0].
The problem is, of course, there is no iter[0]. The iter vector is still empty, at this point.
Additional comments, which is sadly true for at least 50% of these kinds of questions on stackoverflow.com:
1) "using namespace std"; is a bad practice, that should be avoided
2) Do not use system("pause") as well, as you referenced in your question.

Reading number list from file to a dynamic array

I'm having trouble reading a number list from a .txt file to a dynamic array of type double. This first number in the list is the number of numbers to add to the array. After the first number, the numbers in the list all have decimals.
My header file:
#include <iostream>
#ifndef SORT
#define SORT
class Sort{
private:
double i;
double* darray; // da array
double j;
double size;
public:
Sort();
~Sort();
std::string getFileName(int, char**);
bool checkFileName(std::string);
void letsDoIt(std::string);
void getArray(std::string);
};
#endif
main.cpp:
#include <stdio.h>
#include <stdlib.h>
#include "main.h"
int main(int argc, char** argv)
{
Sort sort;
std::string cheese = sort.getFileName(argc, argv); //cheese is the file name
bool ean = sort.checkFileName(cheese); //pass in file name fo' da check
sort.letsDoIt(cheese); //starts the whole thing up
return 0;
}
impl.cpp:
#include <iostream>
#include <fstream>
#include <cstring>
#include <stdlib.h>
#include "main.h"
Sort::Sort(){
darray[0];
i = 0;
j = 0;
size = 0;
}
Sort::~Sort(){
std::cout << "Destroyed" << std::endl;
}
std::string Sort::getFileName(int argc, char* argv[]){
std::string fileIn = "";
for(int i = 1; i < argc;)//argc the number of arguements
{
fileIn += argv[i];//argv the array of arguements
if(++i != argc)
fileIn += " ";
}
return fileIn;
}
bool Sort::checkFileName(std::string userFile){
if(userFile.empty()){
std::cout<<"No user input"<<std::endl;
return false;
}
else{
std::ifstream tryread(userFile.c_str());
if (tryread.is_open()){
tryread.close();
return true;
}
else{
return false;
}
}
}
void Sort::letsDoIt(std::string file){
getArray(file);
}
void Sort::getArray(std::string file){
double n = 0;
int count = 0;
// create a file-reading object
std::ifstream fin;
fin.open(file.c_str()); // open a file
fin >> n; //first line of the file is the number of numbers to collect to the array
size = n;
std::cout << "size: " << size << std::endl;
darray = (double*)malloc(n * sizeof(double)); //allocate storage for the array
// read each line of the file
while (!fin.eof())
{
fin >> n;
if (count == 0){ //if count is 0, don't add to array
count++;
std::cout << "count++" << std::endl;
}
else {
darray[count - 1] = n; //array = line from file
count++;
}
std::cout << std::endl;
}
free((void*) darray);
}
I have to use malloc, but I think I may be using it incorrectly. I've read other posts but I am still having trouble understanding what is going on.
Thanks for the help!
Your use of malloc() is fine. Your reading is not doing what you want it to do.
Say I have the inputfile:
3
1.2
2.3
3.7
My array would be:
[0]: 2.3
[1]: 3.7
[2]: 0
This is because you are reading in the value 1.2 as if you were rereading the number of values.
When you have this line:
fin >> n; //first line of the file is the number of numbers to collect to the array
You are reading in the count, in this case 3, and advancing where in the file you will read from next. You are then attempting to reread that value but are getting the first entry instead.
I believe that replacing your while() {...} with the code below will do what you are looking for.
while (count != size && fin >> n)
{
darray[count++] = n; //array = line from file
std::cout << n << std::endl;
}
This should give you the correct values in the array:
[0]: 1.2
[1]: 2.3
[2]: 3.7
You appear to be writing the next exploitable program. You are mistakenly trusting the first line of the file to determine your buffer size, then reading an unlimited amount of data from the remainder of the file into a buffer that is not unlimited. This allows an evil input file to trash some other memory in your program, possibly allowing the creator of that file to take control of your computer. Oh noes!
Here's what you need to do to fix it:
Remember how much memory you allocated (you'll need it in step #2). Have a variable alleged_size or array_length that is separate from the one you use to read the rest of the data.
Don't allow count to run past the end of the array. Your loop should look more like this:
while ((count < alleged_size) && (cin >> n))
This both prevents array overrun and decides whether to process data based on whether it was parsed successfully, not whether you reached the end-of-file at some useless point in the past.
The less problematic bug is the one #bentank noticed, that you didn't realize that you kept your position in the file, which is after the first line, and shouldn't expect to hit that line within the loop.
In addition to this, you probably want to deallocate the memory in your destructor. Right now you throw the data away immediately after parsing it. Wouldn't other functions like to party on that data too?

Comparing numbers in strings to numbers in int?

I'm trying to make a program that will open a txt file containing a list of names in this format (ignore the bullets):
3 Mark
4 Ralph
1 Ed
2 Kevin
and will create a file w/ organized names based on the number in front of them:
1 Ed
2 Kevin
3 Mark
4 Ralph
I think I'm experiencing trouble in line 40, where I try to compare the numbers stored in strings with a number stored in an int.
I can't think of any other way to tackle this, any advice would be wonderful!
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
using namespace std;
int main()
{
ifstream in;
ofstream out;
string line;
string collection[5];
vector <string> lines;
vector <string> newLines;
in.open("infile.txt");
if (in.fail())
{
cout << "Input file opening failed. \n";
exit(1);
}
out.open("outfile.txt");
if (out.fail())
{
cout << "Output file opening failed. \n";
exit(1);
}
while (!in.eof())
{
getline(in, line);
lines.push_back(line);
}
for (int i = 0; i < lines.size(); i++)
{
collection[i] = lines[i];
}
for (int j = 0; j < lines.size(); j++)
{
for (int x = 0; x < lines.size(); x--)
{
if (collection[x][0] == j)
newLines.push_back(collection[x]);
}
}
for (int k = 0; k < newLines.size(); k++)
{
out << newLines[k] << endl;
}
in.close( );
out.close( );
return 0;
}
Using a debugger would tell you where you went wrong, but let me highlight the mistake:
if (collection[x][0] == j)
You're expecting a string like 3 Mark. The first character of this string is '3', but that has the ASCII value of 51, and that is the numerical value you'll get when trying work with it is this way! This will never equal j, unless you've got a lot of lines in your file, and then your search system will not work at all like you wanted. YOu need to convert that character into an integer, and then do your comparison.
C++ offers many way to process data via streams, including parsing simple datafiles and converting text to numbers and vice versa. Here's a simple standalone function that will read a datafile like you have (only with arbitrary text including spaces after the number on each line).
#include <algorithm>
// snip
struct file_entry { int i; std::string text; };
std::vector<file_entry> parse_file(std::istream& in)
{
std::vector<file_entry> data;
while (!in.eof())
{
file_entry e;
in >> e.i; // read the first number on the line
e.ignore(); // skip the space between the number and the text
std::getline(in, e.text); // read the whole of the rest of the line
data.push_back(e);
}
return data;
}
Because the standard way that >> works involves reading until the next space (or end of line), if you want to read a chunk of text which contains whitespace, it will be much easier to use std::getline to just slurp up the whole of the rest of the current line.
Note: I've made no attempt to handle malformed lines in the textfile, or any number of other possible error conditions. Writing a proper file parser is outside of the scope of this question, but there are plenty of tutorials out there on using C++'s stream functionality appropriately.
Now you have the file in a convenient structure, you can use other standard c++ features to sort it, rather than reinventing the wheel and trying to do it yourself:
int sort_file_entry(file_entry a, file_entry b)
{
return a.i < b.i;
}
int main()
{
// set up all your streams, etc.
std::vector<file_entry> lines = parse_file(in);
std::sort(lines.begin(), lines.end(), sort_file_entry);
// now you can write the sorted vector back out to disk.
}
Again, a full introduction to how iterators and containers work is well outside the scope of this answer, but the internet has no shortage of introductory C++ guides out there. Good luck!

C++ Splitting strings from ifstream and placing them in seperate arrays

I'm writing a program in C++ to take input from a text file (dates and the high/low temp of that day), split the dates and temps into two separate arrays. I have the process down; however, I can't seem to split the strings appropriately. I've tried different methods with getline() and .get, but I need to keep the strings as STRINGS, not an array of chars. I've looked into and read the answers for similar questions using vectors and strtock and there's only one problem: I'm still fairly new, and the more I look into them, the more confused I get.
If I am to use that method in solving my problem, I just need to be pointed in the right direction of how to apply it. Apologies for my noobishness, it's just easy to get overwhelmed with all of the different ways to solve one problem with C++ (which is the reason I enjoy using it so much. ;))!
Sample from text:
10/12/2007 56 87
10/13/2007 66 77
10/14/2007 65 69
etc.
The dates need to be stored in one array, and the temps (both high and low) in another.
Here's what I have (unfinished, but for reference nonetheless)
int main()
//Open file to be read
ifstream textTemperatures;
textTemperatures.open("temps1.txt");
//Initialize arrays.
const int DAYS_ARRAY_SIZE = 32,
TEMPS_ARRAY_SIZE = 65;
string daysArray[DAYS_ARRAY_SIZE];
int tempsArray[TEMPS_ARRAY_SIZE];
int count = 0;
while(count < DAYS_ARRAY_SIZE && !textTemperatures.eof())
{
getline(textTemperatures, daysArray[count]);
cout << daysArray[count] << endl;
count++;
}
Thanks everyone.
Try the following
#include <iostream>
#include <fstream>
#include <sstream>
//...
std::ifstream textTemperatures( "temps1.txt" );
const int DAYS_ARRAY_SIZE = 32;
std::string daysArray[DAYS_ARRAY_SIZE] = {};
int tempsArray[2 * DAYS_ARRAY_SIZE] = {};
int count = 0;
std::string line;
while ( count < DAYS_ARRAY_SIZE && std::getline( textTemperatures, line ) )
{
std::istringstream is( line );
is >> daysArray[count];
is >> tempsArray[2 * count];
is >> tempsArray[2 * count + 1];
}
Here is a simple program that read the formatted input. You can easily replace std::cin with your std::ifstream and do whatever you want with the data inside the loop.
#include <iostream>
#include <string>
#include <vector>
int main ()
{
std::vector<std::string> dates;
std::vector<int> temperatures;
std::string date;
int low, high;
while ((std::cin >> date >> low >> high))
{
dates.push_back(date);
temperatures.push_back(low);
temperatures.push_back(high);
}
}
The magic here is done by std::cin's operator>> which reads up to the first whitespace encountered (tabulation, space or newline) and stores the value inside the right operand.