#include <fstream>
#include <string>
#include <iostream>
#include "Gyvūnas.h"
#include "Maistas.h"
using namespace std;
//-------------------------------------------------------
const char CFm[] = "Maistas.txt";
const char CFg[] = "Gyvūnai.txt";
const int CMax = 100;
//-------------------------------------------------------
//--------------------------------------------------------
void Skaityti (const char CFm[], Maistas M[], int & n);
void Skaityti2 (Gyvūnas G[], int & kg);
//----------------------------------------------------------
int main(){
setlocale (LC_ALL , "Lithuanian");
Maistas M[CMax];
Gyvūnas G[CMax];
int n;
int kg;
Skaityti (CFm, M, n);
Skaityti2 (G, kg);
cout << M[1].ImtiMetus() << " " << n << endl;
system ("PAUSE");
return 0;
}
//----------------------------------------------------------
void Skaityti (const char CFm[], Maistas M[], int & n)
{
string produktas;
double kiekis;
int metai;
int mėnuo;
int diena;
ifstream fd(CFm);
fd >> n;
for (int i = 0 ; i<=n ; i++){
fd >> produktas >> kiekis >> metai >> mėnuo >> diena;
M[i].Dėti(produktas, kiekis, metai, mėnuo, diena);
}
fd.clear ();
fd.close();
}
void Skaityti2 (Gyvūnas G[], int & kg)
{
int narvas;
string pavadinimas;
int skaičius;
int produktas;
int kiekis;
int n;
ifstream fd(CFg);
fd >> n;
for (int i = 0 ; i<=kg ; i++){
fd >> narvas >> pavadinimas >> skaičius >> produktas >> kiekis;
G[i].Dėti(narvas, pavadinimas, skaičius, produktas, kiekis);
}
kg = n;
fd.close();
}
When I set breakpoints it shows that in this part ifstream cannot read variable n from file:
ifstream fd(CFm);
fd >> n;
for (int i = 0 ; i<=n ; i++){
fd >> produktas >> kiekis >> metai >> mėnuo >> diena;
M[i].Dėti(produktas, kiekis, metai, mėnuo, diena);
}
fd.clear ();
fd.close();
Errors are:
std::basic_ios
Filebuffer {_Set_eback=0xcccccccc _Set_egptr=0xcccccccc ...} std::basic_filebuf >
What you have are not errors, just values of the pointers. It seems that you can't open CFm file. Please confirm if you really have Maistas.txt in the working directory (for test, you could just move it to C:\Maistas.txt and then pass "C:\\Maistas.txt" as absolute file path.
Also, there's a way to check if the ifstream is properly opened - you can do that by checking failbit:
ifstream fd(CFm);
if(!fd.good())
{
cerr << "Could not open the file!" << endl;
return;
}
Try rename Gyvūnai.txt to Gyvunai.txt.
Using non-ascii symbols as variable-names and function-names is bad practice (Dėti,skaičius), though Visual Studio allow this, using string literals with non-ascii symbols is even worse - actual char code will depend on encoding of source file and compiler code-page settings. Compiler can treat sources as CP1251 when it's actually UTF-8 and have two chars for ū.
Related
I'm trying to read from the same file from another function but it doesn't work.
I guess the problem is that I'm trying to read from ifstream &input but I don't know the other way to implement that
#include <iostream>
#include <fstream>
using namespace std;
class Student{
public:
char name[40]; // i cant use string
int age;
void Input(ifstream &input)
{
input.getline(name, 40);
input >> age;
}
};
void Read(Student *students, int &numberOfStudents)
{
ifstream input("test.txt");
input >> numberOfStudents;
students = new Student[numberOfStudents];
for (int i = 0; i < numberOfStudents; ++i)
students[i].Input(input);
input.close();
}
int main()
{
int size = 0;
Student *students = NULL;
Read(students, size);
for (int i = 0; i < size; ++i)
cout << students[i].name << endl << students[i].age << endl;
return 0;
}
I made my input file
3
1
2
3
4
5
6
(if the program was working correctly i should've get 1 - name age - 2 etc)
but what i got is no names with ages = 1 2 3 respectively
The program does not work because you define:
void Read(Student *students, int &numberOfStudents)
And then
int size = 0;
Student *students = NULL;
Read(students, size);
The students pointer is passed-by value so Read() can not change the memory address outside the function.
To fix this simply pass the the pointer by-reference:
void Read(Student *& students, int &numberOfStudents)
Lastly as I commented you need to account white space e.g. '\n' line ending
In the file when using >> operator to extract data:
void Input(ifstream &input)
{
input.getline(name, 40);
input >> age;
input.ignore(1);
}
Same for reading the number of students in the file.
This c++ code giving me errors and I dont know how to remove those errors.
code:
#include <iostream>
#include <string>
#include <fstream>
#include <cctype>
#include <iomanip>
using namespace std;
string& RaiseItToUpperCase(string& w)
{
int len = w.length();
for (int index =0; index <len; index++)
w[index]= toupper(w[index]);
return w;
}
void LoadData()
{
string filename;
while(true)
{
cout<<"Enter Data file:";
cin>>filename;
cout<<"Filename entered"<<filename<<endl;
ifstream myfile(filename.c_str());
if(!myfile.good())
{
cout<<"Please Enter a Valid text File"<<endl;
continue;
}
static std::string const targetExtension ("txt");
if (!(filename.size() >= targetExtension.size()
&& std::equal (filename.end() - targetExtension.size(),
filename.end(),
targetExtension.begin() ) ))
{
cout<<"File is not txt"<<endl;
continue;
}
break;
}
string i = filename;
string o;
cout<<"Enter an output file name:"<< endl;
cin>>o;
ofstream output;
ifstream input(filename);
output.open(o.c_str());
int charc =0;
int numw =0;
int longl =0;
int shortl =10000;
while (input>>1)
{
numw++;
charc = charc + i.length() +1;
if (i.length() > longl)
{
longl = i.length();
}
if (i.length() < shortl)
{
i =RaiseItToUpperCase(i);
output << i;
if(input.get() ==32)
{
output<<" ";
}
else
{
output<<"\n";
}
}
charc = charc - 1;
output<<"\nWord Counter Summary\n"<<endl;
output<<"Total Number of Words:"<<numw<<endl;
output<<"Total Number of Characters:"<<charc<<endl;
output<<" Largest Word Size:"<<longl<<endl;
output<<" Smallest Word Size"<<shortl<<endl;
}
}
int main ()
{
LoadData();
return 0;
}
This is c++ file stream program and I am trying to run this code but it giving me errors and i am not able to figure out how remove this errors
so Can anyone tell me how to remove those errors and make this code run
Update
here is the Error:
Error 1 error C2679: binary '>>' : no operator found which takes a
right-hand operand of type 'int' (or there is no acceptable
conversion) c:\users\acer\documents\visual studio
2012\projects\consoleapplication15\consoleapplication15\source.cpp 52 1 ConsoleApplication15
And thanks in advance
What do you want to do in while (input>>1) ?
If you want read out something:
If you want to read to an integer like int8_t (or int16_t / int32_t etc.):
int8_t number = 0;
while (input >> number)
If you want to read to a char:
char ch;
while (input >> ch)
I'm in need of a little debugging. The code is 100% compile-ready. However, it crashes if given either a small fragment of a document to compress, and when it decompresses it gives a error about bounds checking. I'm a little afraid of running it as well. It's not dangerous, but this is my masterpiece as of now. It is right in the sweet spot of compression techniques. This is one I made up. It uses a calculus derivation algorithm to get millions of unique keys to use. These are all predictable. And because they're unique, I can't screw it up by taking a key more than one time in the hashing. The aim of this code is to generate a hash which is perfectly regenerative and gives no loss in the compression. Thank you.
#include <iostream>
#include <bitset>
#include <vector>
#include <cmath>
#include <fstream>
#include <algorithm>
using namespace std;
class S_Rend {
private:
const bitset<8> beta=0xad;
protected:
bitset<8> alpha, lambda, gamma, omega;
bitset<8> delta, eta, theta, ghost, spec;
vector<long> cred;
public:
unsigned int integral;
S_Rend() { delta=0x00; eta=0x00; theta=0x00; lambda=0x00; alpha=0x00; delta=0x00; };
~S_Rend() { };
int s_render(ifstream&,ofstream&);
int render(ifstream&,ofstream&);
long s_nop(long t, int set);
} n;
/*+**- Project::Sailwinds -**+*/
long S_Rend::s_nop(long t,int set) {
if (set) {
integral=0;
t=(long&)beta;
}
integral++;
if (abs(round((t*1.618)*t-(integral+0.618))-1) <= 4294967296)
return (abs(round((t*1.618)*t-(integral+0.618))-1));
else
return (abs(round(sqrt(t))+(round(sqrt(t))*round(sqrt(integral))+1)));
}
int S_Rend::render(ifstream& in, ofstream& out) {
long bn;
long size=0;
long t;
if (!(in.is_open()))
{ return -1; }
else {
t=(long&)beta;
for_each (std::istreambuf_iterator<char>(in), \
std::istreambuf_iterator<char>(), \
[&] (int x) {
t=s_nop((long&)t,0);
cred.push_back(t);
alpha = (long&)cred[size];
delta = (long&)x;
lambda ^= (alpha ^ delta);
lambda ^= beta;
lambda = (int&)lambda + 1;
size++;
});
printf("*");
}
if (out.is_open())
{ out << lambda << endl;
out << size << endl;
out << delta << endl;
out << cred[size-1] << endl; }
else { return -1; }
in.close();
out.close();
return 0;
}
int S_Rend::s_render(ifstream& in, ofstream& out) {
long i, n;
long size;
long t;
long chk;
in >> lambda;
in >> size;
in >> delta;
in >> chk;
t=(long&)beta;
long bn=0;
while (size-1>=bn) {
t=s_nop((long&)t,0);
cred.push_back(t);
bn++;
}
if (cred[bn-1]==chk)
cout << "\nValidity Pass... Success!" << endl;
else {
printf("\nValidity Pass...Fail! %u != %u",cred[cred.size()-1],chk);
return 1;
}
cout << "\nWriting to Buffer..." << endl;
vector<long> btrace;
vector<long> ltr;
bn=1;
while (size-1>=bn) {
ltr.push_back(1);
btrace.push_back(1);
ltr[0]=(long&)lambda;
for (i=1;i<=btrace.size()-1;i++) {
alpha = (long&)cred[size-bn];
ghost = (long&)btrace[i-1];
spec = (long&)ltr[bn] - 1;
spec ^= (int&)beta;
eta = spec | alpha;
theta = spec & alpha;
omega = spec | eta;
gamma = spec & eta;
if ((eta ^ gamma) == (theta ^ omega)) {
printf(".");
ghost = (eta ^ gamma);
btrace[i-1] = (long&)ghost;
}
}
bn++;
}
cout << "One more second..\n";
bn=0;
while (bn<=btrace.size()-1) {
bn++;
delta = (long&)btrace[bn];
out << (const char)(long&)delta;
}
cout << "\nBuffer Written... Exiting..\n";
in.close();
out.close();
printf("*");
return 0;
}
int main() {
string outfile = "";
string infile = "";
string DC = "1";
printf("Enter <C> or <D> to compress or decompress ");
cin >> DC;
printf("\nInput File: ");
cin >> infile;
ifstream in;
in.open(infile.c_str(), std::ios::in | std::ios::binary);
if (in.fail())
return -1;
printf("\nOutput File: ");
cin >> outfile;
ofstream out;
out.open(outfile.c_str(), std::ios::out);
if (out.fail())
return -1;
if ((DC=="c") || (DC=="C"))
bool f=n.render(in, out);
if ((DC=="d") || (DC=="D"))
bool f=n.s_render(in, out);
printf("\nProgram Execution Done.");
n.~S_Rend();
return 0;
}
This last while-loop is accessing index 1 to (and including!) btrace.size():
bn=0;
while (bn<=btrace.size()-1) {
bn++;
delta = (long&)btrace[bn];
out << (const char)(long&)delta;
}
Move bn++; to the end of the loop, like you did in all your other loops.
And i have to agree with user4581301, using <= size-1 instead of just < size looks weird.
(int &)beta is a mistake. This is a reinterpret_cast which violates the strict aliasing rule. Probably it also accesses out of bounds; e.g. bitset<8> may only be 1 byte big, but (int &)beta will read 4 bytes out of that memory location.
Instead you should use beta.to_ulong(). You make the same mistake in dozens of places.
Remove all the casts from your code. Using a cast (especially a C-style cast) tells the compiler "Don't warn me if this is a mistake, I know what I am doing". But in fact you don't know what you are doing. Mostly, C++ can be written without using casts.
(There may be other mistakes too, just this one stood out to me on first reading. Fix all of these and try again).
How can I extract pieces from this string?
I have a file that contains:
0065445 APPLE$456
089464 MANGO$489
0012389 GUAVA$744
What I want to do is input the file line by line, then cut the string into some pieces.
0065455 Will go in a struct a[0].num
APPLE will go in struct a[0].name
456 will go in struct a[0].dollar
And similarly for other lines.
Everything is working fine, but it's not successfully getting the dollar part into its variable.
Here's the code:
#include<cstdlib>
#include<iostream>
using namespace std ;
int main(){
FILE *fp;
fp = fopen("input.txt","r");
char str[80] ;
struct abc{
int num;
char name[20];
int dollar;
};
int i = 0;
while(fgets(str,79,fp)!=NULL){
struct abc a[i] ;
sscanf(str,"%d %[^$]s$%d\n",&a[i].num,a[i].name,&a[i].dollar);
cout <<i+1 <<") Number : "<<a[i].num<<" Name : "<< a[i].name <<" Dollar : "<< a[i].dollar << endl ;
i++;
}
return 0 ;
}
/* These didn't work too.
sscanf(str,"%d %[^$]s %d\n",&a[i].num,a[i].name,&a[i].dollar);
sscanf(str,"%d %[^$]s%d\n",&a[i].num,a[i].name,&a[i].dollar);
sscanf(str,"%d %s$%d\n",&a[i].num,a[i].name,&a[i].dollar);
*/
There's 1 more problem: the first part of string is an int that starts with 0, but the zero is not being accepted in the int. How to do it?
This is working as I want now but still after parasing the string into an int I am not getting the zeroes:
#include<cstdlib>
#include<iostream>
#include<cstring>
using namespace std ;
int main(){
FILE *fp;
fp = fopen("input.txt","r");
char str[80] ;
char temp[80] ;
struct abc{
int num;
char name[20];
int dollar;
};
int i = 0;
int j = 0 ;
while(fgets(str,79,fp)!=NULL){
i = 0;
j = 0 ;
struct abc a[i] ;
char* ptr = 0; // this is used as a helper variable to strtok
ptr = strtok(str, " $\n"); // we specify the delimiters here
while (ptr != NULL)
{
if (j == 0){
strcpy(temp, ptr);
a[i].num = atoi(temp);
}
if (j == 1)
strcpy(a[i].name, ptr);
if (j == 2){
strcpy(temp, ptr);
a[i].dollar = atoi(temp);
}
ptr = strtok(NULL, " $\n");
j++;
}
cout <<i+1 <<") Number : "<<a[i].num<<" Name : "<< a[i].name <<" Dollar : "<< a[i].dollar << endl ;
i++;
}
return 0 ;
}
/* These didn't work either.
sscanf(str,"%d %[^$]s %d\n",&a[i].num,a[i].name,&a[i].dollar);
sscanf(str,"%d %[^$]s%d\n",&a[i].num,a[i].name,&a[i].dollar);
sscanf(str,"%d %s$%d\n",&a[i].num,a[i].name,&a[i].dollar);
*/
Based on the C++ tag, I'd do things a little differently. First I'd overload the stream extractor operator for your abc type:
std::istream &operator>>(std::istream &is, abc &a) {
is >> a.num;
std::getline(is, a.name, '$');
return is >> a.dollar;
}
Then you can use that to read in a file of records, such as:
abc temp;
std::vector<abc> a;
std::ifstream in("input.txt");
while (in >> temp)
a.push_back(temp);
Or, you can use an istream_iterator to initialize a vector directly from the stream:
std::vector<abc> a((std::istream_iterator<abc>(in)),
std::istream_iterator<abc>());
The easiest way to keep the leading zeros on the first number is probably to change it from an int to a std::string.
Use strtok:
Here is a simple code (C only) that prints your strings separately (I recommended a similar solution in another post).
#include <stdio.h>
#include <string.h> // for strcpy and strtok
#include <stdlib.h> // for atoi
int main()
{
char input [25] = "0065445 APPLE$4056"; // input string
// storage for the separate parts of the string
char line[10];
char fruit[10];
char number[10];
char* ptr = 0; // this is used as a helper variable to strtok
ptr = strtok(input, " $\n"); // we specify the delimiters here
int i = 0;
// I'm using i here as a control variable so that during each iteration different part
// of the string is saved
while (ptr != NULL)
{
if (i == 0)
strcpy(line, ptr);
if (i == 1)
strcpy(fruit, ptr);
if (i == 2)
strcpy(number, ptr);
ptr = strtok(NULL, " $\n");
i++;
}
printf("%s %s %s\n", line, fruit, number);
return 0;
}
Some sample output:
$ ./a.out
0065445 APPLE 4056
Is this what you need?
the 0's will not show up when you print the integer a[i].num.
You could make a[i].num a string (char[]) or an integer array. to make the 0's show up. you can parse it as an integer (via atoi(str)), if you need it to be used otherwsie.
#include <iostream>
#include <fstream>
#include <sstream>
struct abc{ int num; std::string name; int dollar; };
int main(int argc, char* argv[]) {
std::ifstream file("input");
abc st1;
std::string l;
while (file >> st1.num >> l) {
if (size_t p = l.find_first_of('$')) {
st1.name = l.substr(0, p);
std::istringstream(l.substr(p+1)) >> st1.dollar;
std::cout << st1.num << " : "
<< st1.name << " : " << st1.dollar << std::endl;
}
}
return 0;
}
I am trying to write an implementation of rc4. I am reading in plaintext from a file using an ifstream. I noticed that it wasn't outputting at the end of the file, so I tried the various ways of explicitly clearing the buffers. No matter which way (using an endl, appending \n, calling cout.flush()) I try to flush the buffer, I get a segfault. As a sanity check, I replaced my code with an example from the web, which I also tested separately. It works if I put it in its own file and compile it (e.g., it prints out the contents of the file, doesn't segfault, and doesn't require any calls to flush() or endl to do so), but not in my code.
Here is the offending bit of code (which works fine outside of my code; its copied pretty much directly from cplusplus.com)
ifstream is;
is.open("plain");
char c;
while (is.good()) // loop while extraction from file is possible
{
c = is.get(); // get character from file
if (is.good())
cout << c;
// cout.flush();
}
is.close(); // close file*/
Here is the full code: (warning, lots of commented out code)
#include <iostream>
#include <fstream>
#include <string.h>
#include <vector>
using namespace std;
static char s[256], k[256];
//static char *i, *j;
void swap(int m, int n, char t[256]){
char tmp = t[m];
t[m] = t[n];
t[n] = tmp;
}
char getByte(){
static char i(0), j(0);
i = (i+1)%256;
j = (j + s[i])%256;
swap(i, j, s);
return s[(s[i]+s[j]) % 256];
}
int main(int argc, char ** argv){
/*string key = argv[1];*/
if(argc < 4){
cout << "Usage: \n rc4 keyfile plaintextfile outputfile" << endl;
return -1;
}
string key;
ifstream keyfile (argv[1]);
keyfile >> k;
cout << "Key = " << k << endl;
keyfile.close();
/*ifstream plaintextf;
plaintextf.open(argv[2]);*/
ofstream ciphertextf (argv[3]);
for(int q = 0; q < 256; q++){
s[q] = q;
}
int i, j;
for(int m = 0; m < 256; m++){
j = (j + s[m] + k[m % sizeof(k)])%256;
swap(m, j, s);
}
// vector<char> bytes(plaintext.begin(), plaintext.end());
// bytes.push_back('\0');
// vector<char>::iterator it = bytes.begin();
/* char pt;
while(plaintextf.good()){
pt = plaintextf.get();
if(plaintextf.good()){
cout << pt;
ciphertextf <<(char) (pt ^ getByte());
}
} */
ifstream is;
is.open("plain");
char c;
while (is.good()) // loop while extraction from file is possible
{
c = is.get(); // get character from file
if (is.good())
cout << c;
// cout.flush();
}
is.close(); // close file*/
/*// plaintextf.close();
ciphertextf.close();
keyfile.close();
*/
return 0;
}
Additionally, I think the second call to is.good() [ as in if(is.good()) ], would prevent the very last character of the file from being copied.