C++ Benford's Law program. - c++

So I have to write a program to
=> analyze three different data files, and try to confirm Benford’s law. You will create a console application that opens each file, counts the number of values that start with ‘1’, ‘2’, ‘3’, etc., and then outputs the percentages of each digit.
I think I have it down but I keep getting an error in Dev C++.
int analyzeData(string fname) {
ifstream infile(string fname);
int tmp,count = 0;
float percents[9];
int nums[9] = { 0 };
if(!infile.good())
return 1;
while(!infile.eof())
{
infile >> tmp;
tmp = first(tmp);
if(tmp > 0)
{
nums[tmp - 1] ++;
count++;
}
}
It's saying that 'good', 'eof', and 'infile' are non-class type?
I don't know what that means!
Help would be much appreciated! thanks!

Firstly
ifstream infile(string fname);
should be
ifstream infile(fname);
Your version was a function prototype not a declaration of a variable.
Secondly this is the wrong way to loop to the end of a file
while (!infile.eof())
{
infile >> tmp;
...
}
this is the right way
while (infile >> tmp)
{
...
}
This must be the single most common error we see here. eof does not do what you think it does, and anyone who told you to write while (!infile.eof()) is just wrong.
Finally first(tmp) is not the correct way to get the first digit from an integer. You'll have to work a little harder than that.

Rather than read the input as integers, read the lines as strings, the grab the first digit from the string. Or you could read as an integer and then divide tmp by 10 until the result is < 10.
Make you life a little easier, and use the digit as an index into the array. You need to be able to index values 1 - 9, so you would need to declare your array a little bigger. ditto for percents.
int nums[9] = { 0 }; // works, but do less work
float percents[9];
int nums[10] = { 0 }; // do this, then you can us the digit to index nums[]
float percents[10];
You don't need the guard for tmp > 0, because you have room for all 10 digis,
//if( tmp > 0 )
//{
...
//}
You don't need to subtract one from tmp,
int analyzeData(string fname)
{
ifstream infile(fname);
int tmp,count = 0;
float percents[10];
int nums[10] = { 0 };
if(!infile.good())
return 1;
while(infile >> tmp)
{
tmp = first(tmp);
{
nums[tmp] ++;
count++;
}
}
if(count<1) count=1; //avoid division by zero
for( tmp=1; tmp<10; ++tmp )
cout<<tmp<<":"<<nums[tmp]<<",pct:"<<(nums[tmp]*1.0)/count<<eol;
}

Related

Getting string from file and split that

I'm trying to find the fastest way for getting numbers from file. There can be negative numbers. My e.x. input:
5 3
-5 -6 2 -1 4
1 2 3 4
4 3 2 1
I'm using:
getline(cin, line);
istringstream linestream(line);
linestream >> var;
The result is okay but my program has run time error with last test, maybe min. 100 000 numbers. My question is, is there a faster way to get string and split it to numbers than my solution? The time is the most important.
If there's only numbers in your input, you could do:
std::vector<int> numbers;
int i;
while(cin >> i) {
numbers.push_back(i);
}
To stop the input from cin you'll need to send the EOF (End Of File) signal, which is either Ctrl+D or Ctrl+Z depending on your OS.
The input from a file will automatically stop when the end of the file is reached.
See c++ stringstream is too slow, how to speed up?
For your runtime error, you didn't post compilable code, and your error is in what you didn't post.
The best is make a function that reads a file line by line and puts each line elements in an array( if you are just printing just print it dont store in an array).I am using c function instead of c++ streams because for large data they are faster.The function should use fgetc which is faster than fscanf when used for large data.If in your system fgetc_unlocked works fine then you should replace that to fgetc
-5 -6 2 -1 4
1 2 3 4
Assume the input is like above and is stored in input.txt. Just make the input.txt in your dir and run the following code in the same dir. You can make changes later how you want to use the numbers
#include<iostream>
#include<cstdio>
using namespace std;
#define GC fgetc // replace with fgetc_unlocked if it works in your system(Linux)
//This function takes a line of f and put all integers into A
//and len is number of elements filled
void getNumsFromLine( FILE* f, int *A, int& len){
register char ch=GC(f);
register int n=0;
register bool neg = false;
len=0;
while( ch!='\n' ){
while( ch !='-' && (ch>'9' || ch<'0') ) ch=GC(f);
if( ch=='-') {
neg = true;
ch = GC(f);
}
while( ch>='0' && ch<='9' ){
n = (n<<3)+(n<<1)+ch-'0';
ch = GC(f);
}
if(neg) {
n=-n;
neg=false;
}
A[len++]=n;
n=0;
}
}
int main(){
FILE* f=fopen("input.txt", "r");
int A[10][2],len;
for( int i=0; i<2; i++ ){
getNumsFromLine( f, A[i], len );
for( int j=0; j<len; j++ ) cout << A[i][j] <<" ";
cout << endl;
}
fclose(f);
return 0;
}

Read complex numbers (a+bi) from text file in C++

i want to read an array of complex numbers (in a+bi form). There are several suggestions I found on the internet, however those methods only result the real part, while the imaginary part is always 0. And infact the real part of the next number is the imaginary of the previous number.
For example, I have an text file as follow:
2+4i
1+5i
7+6i
And here is a suggestion for reading complex data
int nRow = 3;
std::complex<int> c;
std::ifstream fin("test.txt");
std::string line;
std::vector<std::complex<int> > vec;
vec.reserve(nRow);
while (std::getline(fin, line))
{
std::stringstream stream(line);
while (stream >> c)
{
vec.push_back(c);
}
}
for (int i = 0; i < nRow; i++){
cout << vec[i].real() << "\t" << vec[i].imag() << endl;
}
while (1);
return 0;
And the output result is:
2 0
4 0
1 0
Is there a proper way to read a+bi complex numbers from text file? Or do I have to read the data as a string, and then process the string to extract and convert it back to complex numer?
Thanks !
One option is to read separately the real and imaginary part in 2 ints, and the sign into a char, then emplace_back into the complex vector, like
int re, im;
char sign;
while (stream >> re >> sign >> im)
{
vec.emplace_back(re, (sign == '-') ? -im : im);
}
Here sign is a char variable that "eats" up the sign.
FILE *fp;
char line[80];
int a, b;
if ((fp = fopen("filename", "r") != NULL)
while (fgets(line, 80, fp) != NULL) {
if (sscanf(line, "%d + %di", &a, &b) == 2)
/* do something with a and b */
else
fprintf(stderr, "Not in a+bi form");
}
Your requirement (the format of input you seek) does not correspond to the method you are using to read it. The default streaming of a complex is the real and the imaginary part separated by spaces and in brackets - the sign between is not mandatory, and the trailing i is not required.
The obvious way to parse for input you seek is to read the real part, read a character, check if the character is a signed (+ or -) and ignore spaces, then read the imaginary part. That is trivial with istreams.
int real[10] = { 0 };
int imaginary[10] = { 0 };
FILE *lpFile = fopen("filename" "rt"); // Open the file
for (int i = 0; i < 10; i++) {
fscanf(lpFile, "%d+%di", &real[i], &imaginary[i]); // Read data 10 times
}
fclose(lpFile); // Close the file
This example code will read 10 complex numbers from a file.

loading values of a text file into an array

The text file I generate from an graph generator is similar to:
:0 0|- 1|82 2|72
:1 0|87 1|- 2|74
:2 0|86 1|53 2|-
These are supposed to represent node and the distance to them.
line 1 is :1 1|- 2|82 3|72
it is saying the distance from node 0 to node 0 (0|-) is - (infinity)
and from node 0 to node 1 (1|82) is 82
and from node 0 to node 2 (2|72) is 72
But I want to load the values into a 2d array.
the array above should be
Graph[0][0] = -
Graph[0][1] = 82
Graph[0][2] = 72
etc...
I'm just not sure how when I read in the txt file to catch the :0 & :1 & :2 then separate 1|5.
any help would be great!
Thanks!
One problem is those - characters. If you replace them with 0, then you can use something like the following code:
// Open the file like this:
// std::ifstream fin ("whatever.txt");
char dummy;
for (int i = 0; i < n; ++i)
{
int x, d;
fin >> dummy >> x; // read ":1", etc.
assert (dummy == '=');
assert (x == i + 1);
for (int j = 0; j < n; ++j)
{
fin >> x >> dummy >> d; // read "2|42", etc.
assert (dummy == '|');
assert (x == j + 1);
Graph[i][j] = d;
}
}
All those asserts are there to make sure the redundant data in the file are as they are supposed to be. And don't forget to replace all '-'s with '0's.
You can see what I'm doing there. I'm reading the integers normally, and reading a character when the ':' and '|' symbols are.
A plain C approach which you may re-write as C++ or just use as-is. After all, this doesn't look like C++ critical code.
Note the use of a maximum length for fgets (granted, a C++ string could work better here) and a #define for "infinity", since you cannot store this value in a sensible way. It assumes all of your distances are positive, and that your data is as you have shown (i.e., no surprises such as huge numbers > MAX_INT, or inconsistent spacing).
The usual C++ approach of cin does not work well here, and neither does fscanf, since in both cases you need to read one character, determine if it is an - and if it is not re-read itself and any digits following it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DATA_LENGTH 120
#define DIST_INFINITY 0xFFFFFFFF
unsigned int Graph[10][3];
int main (void)
{
FILE *fp;
char input_string[MAX_DATA_LENGTH], *token_ptr;
int graph_counter = 0, i;
fp = fopen ("graph.txt", "rt");
if (!fp)
{
printf ("data not found\n");
return -1;
}
do
{
if (fgets (input_string, MAX_DATA_LENGTH, fp) == NULL)
break;
token_ptr = input_string;
for (i=0; i<3; i++)
{
token_ptr = strchr (token_ptr, '|');
if (!token_ptr || !token_ptr[1])
break;
token_ptr++;
if (*token_ptr == '-')
Graph[graph_counter][i] = DIST_INFINITY;
else
Graph[graph_counter][i] = strtoul (token_ptr, NULL, 10);
token_ptr++;
}
if (i < 3)
break;
graph_counter++;
} while (1);
for (i=0; i<graph_counter; i++)
printf ("Graph[%d] = %u %u %u\n", i, Graph[i][0], Graph[i][1], Graph[i][2]);
return 0;
}

how to read characters and integers from a file?

So I have a data file that looks something like this:
x + y + z
30 45 50
10 20 30
The only characters I needed was the operators, so '+' '+' I was able to use file.get() to successfully get those characters and put them in an array. Problem is I need to get the next line of numbers, and assign them to the values x , y z . I know I cant use .get() , I would have to use getline. Will i have to eliminate the file.get() and use getline instead for first part also?
I looked at some of the questions posted on here but none of them were quite like mines. Note I'm actually going to be using these values for another part of my program, just used cout to see if my values were being read correctly
Here's my previous code:
main(int argc, char *argv[])
{
int a=0;
int n;
fstream datafile;
char ch;
pid_t pid;
int a, b, c, result;
string line;
datafile.open("data1.txt");
if(datafile)
{
for(int i=0; i <9; i++)
{
datafile.get(ch);
if (ch == '*'||ch == '/'||ch == '+'||ch == '-')
{
operations[a] = ch;
cout<<operations[a];
a++;
}
}
}
else
cout<<"Error reading file";
}
So this is how I was getting the first line of the file in the beginning. It worked like I wanted it to, may have not been the nicest coding but it worked. Nevertheless I tried to get the rest of the file, this time using getline, but instead of getting the numbers I was getting a bunch of random gibberish/numbers. I know if I use getline, the first line cannot be in my loop. I know this is how I would get the numbers.
while(getline(datafile, line))
{
istringstream ss(line);
ss >> x >> y >> z;
cout<<x<<""<<y<<""<<z;
}
Would the following make sense for the first line, or am I missing something:
string input;
std::getline(datafile, input)
for (int i = 0; i < input.size(); i++)
if (input[i] == '+' || ...)
{
operations[a] = input[i];
a++;
}
If you don't want to use getline, you could simply read the entire file stream (note that the bool is a rather naive way to handle the problem, I'd recommend something more elegant in your actual code):
bool first = true;
string nums;
int lines = 0;
vector<vector<int>> numlines;
vector<int> topush;
while (!datafile.eof())
{
char ch = datafile.get()
if (ch == 12 && first) //I don't know if '\n' is valid, I'd assume it is but here's the sure bet
first = false;
else if (first && (ch == '+' || ...))
{
operator[a] = ch;
a++;
}
else if (!first && (ch >= '0' && ch <= '9'))
{
if (!(datafile.peek() >= '0' && datafile.peek() <= '0'))
{
numlines[lines].push_back(atoi(nums.c_str());
nums.clear();
if (datafile.peek() == 12)
{
numlines.push_back(topush);
lines++;
}
}
else
nums = nums + ch;
}
Honestly, I can't be sure the above will work exactly right, I'd recommend you just modify your code to use getline exclusively. You'll need to add #include to get atoi.
Add this to your code:
while(!datafile.eof()){
string s;
getline(datafile, s);
istringstream in(s);
string tmp;
while(in >> tmp){
int i = stoi(tmp)
//Do something with i....
}
}

read an input file using vectors

I have written a code to read file below but its not working.
Input file:
2 1 16
16 0 0
1 1 1234
16 0 0
1 1 2345
code is:
std::ifstream input_file;
evl_wire wire;
int num_pins,width,cycles,no;
std::vector<int>IP;
while(input_file)
{
input_file >> num_pins;//num_pins=2
if (pins_.size() != num_pins) return false;
for (size_t i = 0; i < pins_.size(); ++i)
{
input_file >> width;//width=1 for 1=0 ,=16 for i=2
if (wire.width != width) return false;
pins_[i]->set_as_output();
}
for (size_t i = 1; i < file_name.size(); i=i+1)
input_file>>cycles;
input_file>>no;
pins_=IP;
}
where std::vector<pin *> pins_; is in gate class and void set_as_output(); is in pin class
2 represent no of pins,1 width of first pin and 16 width of second pin.
here from second line in file 16 is no of cycles pins must remain at 0 0,for next 1 cycle pins must be assigned 1 and 1234 as inputs.
Some parts of your code are almost certainly wrong. Other parts I'm less certain about -- they don't make much sense to me, but maybe I'm just missing something.
while(input_file)
This is almost always a mistake. It won't sense the end of the file until after an attempt at reading from the file has failed. In a typical case, your loop will execute one more iteration than intended. What you probably want is something like:
while (input_file >> num_pins)
This reads the data (or tries to, anyway) from the file, and exits the loop if that fails.
if (pins_.size() != num_pins) return false;
This is less clear. It's not at all clear why we'd read num_pins from the file if we already know what value it needs to be (and the same seems to be true with width vs. wire.width).
for (size_t i = 1; i < file_name.size(); i=i+1)
input_file>>cycles;
This strikes me as the most puzzling part of all. What does the size of the string holding the file name have to do with anything? This has be fairly baffled.
I don't fully understand your code, but I don't see you are opening the input file anywhere. I think it should be:
std::ifstream input_file;
evl_wire wire;
int num_pins,width,cycles,no;
std::vector<int>IP;
input_file.open("name of the file");
if(input_file.is_open())
{
while(input_file >> num_pins) //num_pins=2
{
if (pins_.size() != num_pins) return false;
for (size_t i = 0; i < pins_.size(); ++i)
{
input_file >> width;//width=1 for 1=0 ,=16 for i=2
if (wire.width != width) return false;
pins_[i]->set_as_output();
}
for (size_t i = 1; i < file_name.size(); i=i+1)
input_file>>cycles;
input_file>>no;
pins_=IP;
}
input_file.close();
}
The function I used:
bool input::validate_structural_semantics()
{
evl_wire wire;
std::ifstream input_file;std::string line;
int x[]={1000};
for (int line_no = 1; std::getline(input_file, line); ++line_no)
std::string s; int i=0;
std::istringstream iss;
do
{
std::string sub;
iss >> sub;
x[i]=atoi(sub.c_str());
i++;
}
while (iss);
if (pins_.size()!=x[0]) return false;
for (size_t i = 0; i < pins_.size(); ++i)
{
if (wire.width != x[i+1]) return false;
pins_[i]->set_as_input();
}
for(size_t i=4;i<1000;i++)
{
for(size_t j=0;j<pins_.size();j++)
pins_.assign(x[i-1],x[i+j]);
}
return true;
}
This implementation is using arrays but it didn't work,although there isn't any compling error.