How to incorporate a large list of numbers into a c++ code [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have four lists each containing 84 different rates which I want to be able to access using if/else statements based on the inputted information and I was hoping there was something more efficient than typing each one into an array.
What would be the easiest way to do this? Any hints would be very helpful I just need a starting point.
#include "MaleNonSmoker.txt"
using namespace std;
double ratesmn[85] = {
#include "MaleNonSmoker.txt"
- 1
};
#include <iostream>
#include <string>
#define STARTAGE 15
int main() {
double const *rates;
rates = ratesmn;
int age;
cout << "How old are you?\n";
cin >> age;
double myrate = ratesmn[age - STARTAGE];
return 0;
}
The errors that I am getting are from line 1: syntax error: 'constant'
and from line 7: 'too many initializers'

If the numbers do not change, there is no real need to read the numbers at runtime from a file. You can also use them at compile time.
Create four files with the arrays with any tool you like, but a comma after each number so it looks like this:
51,
52,
53,
In your c++ code, define 4 arrays, and use #include to include the numbers from the text file;
int ratesms[85] = {
#include "ratesms.txt"
-1 // add another number because the txt file ends with a comma
};
Do the same for the other arrays.
In your code determine which list you want to use, and set a pointer to that list, for example
int const *rates;
if ( /* smoking male */ )
rates = ratesms;
else if ( /* other variations */ )
rates = ...
And then use it like this;
#define STARTAGE 15
int age=35; // example
int myrate=rates[age-STARTAGE];
If you don't want to substract the start age from the array index, you can also add 15 dummy numbers to the array;
int ratesms[100] = {
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
#include "ratesms.txt"
-1 // add another number because the txt file ends with a comma
};
now ratesms[15] will contain the first number from the txt file.

You can define an array of numbers in C++ like this:
int[6] rates = {1, 2, 3, 4, 5, 6};

What's the format of your "lists?"
Reading them in should be very simple -- check out this tutorial on file I/O in C++. If you save your lists as simple .txt files, you can read each list item line by line by creating an ifstream and calling getline(). The file data will be read as strings, so you can use stoi() and stod() to convert them to integers and doubles, respectively (check out the string reference for more conversion methods).
You also might want to look into saving your excel files as comma-separated-value (.csv) files, which can then be read in line by line in the same manner. Each line will represent a row with cell values separated by commas, which are very easy to parse.

Related

Reading from 3 column txt file to different arrays [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to read a three column and N row txt file to three different arrays:
int N=100;
double x[N],
y[N],
z[N];
ifstream reading;
reading.open("reading.txt");
reading.close();
What should I write in the empty region? x[j], y[j], z[j] should be element in j'th row and first, second and third column respectively.
Once you get the input file stream, it will be similar to reading from a standard input.
As a hint I can say, what about reading every integer and then store them appropriately. For example,
1 2 3
4 5 6
7 8 9
Now you read everything like this
while (redaing>> num) {
// here you would know whether you are reading the first number
// or second number or third.
// x[xi] = num or y[yi]=num or z[zi]=num
}
Also you need to do something before you start reading from a file using the input file stream.
Have this check to make the program more safe.
if (!reading) {
cerr << "Unable to open file reading.txt";
exit(1); // call system to stop
}
A solution would be like this:
int xi=0,yi=0,zi=0,iter=0;
while(redaing >>num){
if(iter%3==0)x[xi++]=num;
else if(iter%3 ==1)y[yi++]=num;
else
z[zi++]=num;
iter++;
}
More succintly as pointed by user4581301
while(redaing >>x[xi++]>>y[yi++]>>z[zi++]){
//..do some work if you need to.
}
Also another from comment to limit the 100 line reading is [From comment of user4581301]
int index = 0;
while(index < 100 && redaing >>x[index]>>y[index]>>z[index] ){
index++;
}
A better solution:
vector<int> x,y,z;
int a,b,c;
while(reading>>a>>b>>c){
x.push_back(a);
y.push_back(b);
z.push_back(c);
//..do some work if you need to.
}
I'm kind of confused on the wording of your question could you try and reword It? Also if you want to read to the nth row I would use a while loop with the condition being while not end of file. Also you may consider using a vector since you don't know how large of an array you want to create.
A trivial way is
Read the file line by line using getline().
Get the line into an istringstream.
Use istringstream as any istream like cin, it will only contain one line of text.
I would suggest you to search for these terms on some website like www.cppreference.com if you don't know them.

Modifying specific characters in text input (C++) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I receive text with special characters (such as á) so I have to manually search and replace each one with code (in this case "á")
I would like to have code to search and replace such instances automatically after user input. Since I'm a noob, I'll show you the code I have so far - however meager it may be.
// Text fixer
#include <iostream>
#include <fstream>
#include <string>
int main(){
string input;
cout << "Input text";
cin >> input;
// this is where I'm at a loss. How should I manipulate the variable?
cout << input;
return 0;
}
Thank you!
An easy method is to use an array of substitution strings:
std::string replacement_text[???];
The idea is that you use the incoming character as the index into the array and extract the replacement text.
For example:
replacement_text[' '] = " ";
// ...
std::string new_string = replacement_text[input_character];
Another method is to use switch and case to convert the character.
Alternative techniques are a lookup table and std::map.
The lookup table could be an array of mapping structures:
struct Entry
{
char key;
std::string replacement_text;
}
Search the table using the key field to match the incoming character. Use the replacement_text to get the replacement text.

C++ Calculator With Unlimited Inputs [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Hi I am a beginner to the c++ language and I would like to know if there is any way of writing a program with unlimited inputs. For example: I want to write a calculator program just to add numbers. That's easy enough but is there a way so that the user can add as many numbers as he wants without being asked how many numbers he wants. Such that if he wants to add three numbers he can just type "1+1+1" or if he wants to add four numbers he adds "+1" to the end of the previous line.Like this the user is not stuck to a fixed number of inputs or so he doesn't need to be asked how many inputs he wants. What functions in c++ do I need to know in order to do this
You can use a while loop to read from standard input. (std::cin) Some basic code to read from a while loop, and add the input to a sum is as follows:
#include <iostream>
#include <string>
#include <cstdlib>
int main(){
std::string line = "";
double sum = 0.0;
while(line != "end"){
std::cout<<"The current sum is: "<<sum<<std::endl;
std::cout<<"Enter the number you would like to add or \"end\" to exit: ";
std::cin>>line;
sum += atof(line.c_str());
}
std::cout<<"The final sum is: "<<sum<<std::endl;
}
This will read numbers until it receives the input "end".
For parsing and evaluating expressions that include infix operators, few things are simpler than the Shunting Yard Algorithm.
Implementing this in C++ is scarcely different than any other language with a container library (or built-in support) that provides stacks and queues. Here, you'll want to use std::stack and std::queue. The input to your program could be a single line (containing an expression typed by the user) read from std::cin (standard input, or the console) into an std::string.
This will not only permit expressions of any reasonable length, but also correctly handle arbitrary nesting of parenthesized sub-expressions, evaluation of special functions, and custom operators.
Yes. It is possible. You can use vector of ints. Get user's input and calculate sum of elements from vector. Put this in loop and that is what you wanted.
try this:
#include <iostream>
int main (int argc, char *argv[])
{
for (int i = 0; i < argc; i++)
std::cout << "argument " << i << " is " << argv[i] << std::endl;
return 0;
}

What's the easiest way to parse this data?

For my game, I'm creating a tilemap that has tiles with different numeric ids, such as 1, 28, etc. This map data is saved into a .dat file that the user edits, and looks a little bit like this:
0, 83, 7, 2, 4
Now in order for the game to generate the correct tiles, it must see what the map data is obviously. What I want this small parser to do is to skip over whitespace and the commas, and fetch the numeric data. Also, I want it to be in a way that I can get not only single digit id numbers, but 2-3 digits as well (83, etc).
Thanks for any and all help!
Sounds like a job for the strtok function:
#include <stdlib.h>
#include <string.h>
int parseData(char* data, size_t maxAllowed, int* parsedData) {
char * pch;
pch = strtok (data," ,");
int idx = 0;
while (pch != NULL)
{
parsedData[idx++] = atoi(pch); //convert to integer
if (i == maxAllowed) {
break; //reached the maximum allowed
}
pch = strtok (NULL, " ,");
}
return i; //return the number found
}
//E.g.
char data[] ="0, 83, 7, 2, 4";
int parsedData[5];
int numFound = parseData(data,5,parsedData);
The above sample will remove all spaces and commas, returning an integer value for each found along with the total number of elements found.
Reading the file could be done easily using C functions. You could read it either all at once, or chunk by chunk (calling the function for each chunk).
This is CSV parsing, but easy is in the eye of the beholder. Depends on whether you want to "own" the code or use what someone else did. There are two good answers on SO, and two good libraries on a quick search.
How can I read and parse CSV files in C++?
Fast, Simple CSV Parsing in C++
https://code.google.com/p/fast-cpp-csv-parser/
https://code.google.com/p/csv-parser-cplusplus/
The advantage of using a pre-written parser is that when need some other feature it's probably already there.

Create an array with external file in C++

I have 4 days of training in C++, so bear with me.
Two data files are required to evaluate a multiple-choice examination. The first file
(booklet.dat) contains the correct answers. The total number of questions is 50. A sample
file is given below:
ACBAADDBCBDDAACDBACCABDCABCCBDDABCACABABABCBDBAABD
The second file (answer.dat) contains the students’ answers. Each line has one student
record that contains the following information:
The student’s answers (a total of 50 answers) in the same format as above (* indicates no answer)., followed by Student ID and Student Name. Example:
AACCBDBC*DBCBDAAABDBCBDBAA*BCBDD*BABDBCDAABDCBDBDA 6555 MAHMUT
CBBDBC*BDBDBDBABABABBBBBABBABBBBD*BBBCBBDBABBBDC** 6448 SINAN
ACB*ADDBCBDDAACDBACCABDCABCCBDDABCACABABABCBDBAABD 6559 CAGIL
I have a homework assignment to write a C++ program that counts the total number of correct answers by each student and outputs this information to another file called report.dat. In this file, the student’s IDs, names and scores must be given. Each correct answer is worth 1 point. For the sample files given above, the output should be as follows:
6555 MAHMUT 10
6448 SINAN 12
6550 CAGIL 49
Here's what I have so far:
include <iostream>
include <fstream>
using namespace std;
int main()
{
char booklet[50] answers[50]
int counter
// Link answers with booklet.dat
booklet = ifstream
input_file("booklet.dat");
return 0;
// Link answers with answers.dat
answers = ifstream
input_file("answer.dat");
return 0;
while (booklet==answers)
{
counter++
cout << "The student had">>counter>> "answers right";
}
}
I'm not even sure I am in the correct direction. I know I need to create an array from the file booklet.dat and another one from the file answer.dat. Then the comparison has to be made and the matches between the two have to be counted.
I don't expect anyone to do the assignment for me, i just need a nudge in the right direction.
1.) On your Syntax:
a) Each line in C++ has to end with an ";". There are some lines in your excample which don't. (Normally your compile should point at this or the following line with an error)
b) Multiple variable definitions need a "," in between two different variables.
2.) I would recommend you to use something like that:
(have a look at C++ Reference fstream)
EDIT: just a little outline, which is not complete in this form, just to give you and idea ;-)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
int nr_of_students = 1000; /* Or any number you'd like to analyze */
int stud_nr[nr_of_students];
string stud_name[nr_of_students];
int stud_count[nr_of_students];
fstream in_out;
in_out.open("filename.dat",fstream::in); // fstream::in for reading from file
// fstream::out for writing to this file
if(in_out.is_open())
{
for(lines=0;(in_out>>answers && lines<nr_of_students);lines++)
{
in_out >> stud_nr[lines]; /* EDIT: sorry hat some index confusions here... */
in_out >> stud_name[lines];
stud_count[lines]=0;
for(int i=0;i<50;i++)
{
/* comparison between the booklet_array and the answers_array */
/* Count up the stud_count[lines] for each right comparison */
}
}
/* some simmilar code for the output-file */
}
else cout << "Error reading " << "filename.dat" << endl;
return 1;
}
3.) Your code would also get more performance with vectors.
A good Tutorial would be: Tutorial part I
and you find part 2 in the comments there
4.) you can achieve a more dynamic code with argc and argv**, just google for that
I hope these comments help you a little bit to carry on ;)
You are already on the right direction. Basically you want to load the answer key into an array for fast comparison and then you need to check the answers of each student and each time they get a correct answer you increment a counter and write the ID, name and score for each student. There are problems with your code such as missing semicolons.
Also please note that returning exits a function and that no statements after an unconditional return are executed, returning from main terminates your program.
The normal approach to open a file for reading is:
#include<fstream>
#include<string>
int main()
{
std::ifstream input_file("inputfilename");
// since the answer key is one line
// and each students answer , id and name are also one line
// getting that line using std::getline() would be sufficient
std::string line;
std::getline(input_file, line);
// line would now contain the entire first line except the newline character
std::getline(input_file, line);
//now line would now contain the second line in the file
return 0;
}
Writing to a file is similar we use ofstream to open a file for writing.
Like so:
#include<fstream>
int main()
{
std::ofstream output_file("outputfilename");
// lets say we have a string and an int that we want to write
std::string line_to_write("Hello File");
int number = 42;
output_file << line_to_write << number; // writes the string and then 42 on the same line
output_file << '\n'; // writes the newline character so that next writes would appear on another line
return 0;
}
For references to the standard library and C++ in general when you need to know the available functions to do something I recommend cppreference here are the specific pages on ifstream and ofstream.