Reading from 3 column txt file to different arrays [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 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.

Related

Read from mixed data file add items to string array and two-dimensional int array C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a text file that looks like this:
January 35 45
February 45 55
etc...
I am trying to read through the file and add each month to a string array and then each following integer into a 2-dimensional array.
I have a months[] array and a temps[][] array.
I'm trying something like this
int size = 0;
while(!file.eof()) {
file >> months[size];
size++;
}
I can't figure out how to add the two integers into the int array...
This is for a class, surprise surprise, the requirements are specifically to read the data from the file and insert the month into an array and the two following integers into the two-dimensional array.
We have not gone over structures or vectors yet.
Don't use arrays. Model with a structure.
struct Month_Record
{
std::string month_name;
int value_1;
int value_2;
};
Next, add a method to input the structure:
struct Month_Record
{
//... same as above
friend std::istream& operator>>(std::istream& input, Month_Record& mr);
}
std::istream& operator>>(std::istream& input, Month_Record& mr)
{
input >> mr.month_name;
input >> mr.value_1;
input >> mr.value_2;
return input;
}
You input becomes:
std::vector<Month_Record> database;
Month_Record mr;
while (input_file >> mr)
{
database.push_back(mr);
}
You can access the database like an array:
std::cout << database[0].month_name
<< ", " << database[0].value_1
<< ", " << database[0].value_2
<< "\n";
A nice feature to the model is that you can have the record in one cache line. With parallel arrays, the processor may have to reload the data cache to fetch data from the other arrays (because the entire array may have to be loaded into the cache).
int size = 0;
while(size < MAX_ARRAY_LENGTH && // prevent overflow.
// Will stop here if out of space in array
// otherwise && (logical AND) will require the following be true
file >> months[size] // read in month
>> temps[size][0] // read in first temp
>> temps[size][1]) // read in second temp
{ // if the month and both temperatures were successfully read, enter the loop
size++;
}
MAX_ARRAY_LENGTH is a constant defining the maximum number of months that can be placed in the arrays.
>> returns a reference to the stream being read so you can chain the operations together and take advantage of the stream's operator bool when done reading. operator bool will return true if the stream is still in a good state.
The logic looks like
loop
if array has room
read all required data from stream
if all data read
increment size
go to loop.
You may want a test after end of the loop to make sure all of the data was read. If you're reading to the end of the file, something like if (file.eof()) will make sure the whole file was read. If you want a year's worth of data, if (size == ONE_YEAR) where ONE_YEAR is a constant defining the number of months in a year.

Add integers to array using cin simultaneously in 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 5 years ago.
Improve this question
Hellow guys i want to add nine integers to array at once time without pressing enter key in run time. please guys tell me how to add nine integers to array simultaneously in C++.
Thanks!
If you want to process each integer value right after its input in console is complete (e.g. in that a blank indicates that the next integer value shall begin), you are in a bad position.
The reason is that terminal input (beyond of what your C++ program can influence) often is buffered, and even cin might not receive any character until Enter or EOF is pressed in the terminal.
There may exist workarounds like conio.h or ncurses, but the are not standard and probably not worth the effort in your situation unless you really need to implement integer scanning for a production environment tightly connected to console input.
Try it out and compare input taken directly from console to input from a stream that is already "filled" with enough input:
int main() {
stringstream ss("12 34 56 78 90 10 11 12 13");
//istream &in = ss; // would output each integer immediately.
istream &in = cin; // will probably wait for enter before processing begins.
int value = 0;
for (int i=0; i<9; i++) {
if (! (in >> value))
break;
cout << value << "; ";
}
}

How to incorporate a large list of numbers into a c++ code [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 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.

Simple text editing program in C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I got a little bit of trouble creating a program that edits text in C++. Keep in mind that I'm still at the beginning of programing. Here is what I must do:
Some text is placed in text file F. I must write a program-editor, which based on the file F, commands and data from the keyboard creates the file FF. The program-editor must recognize and process the following commands:
AN - insert text after the n-th row;
IN - insert text before the n-th row;
CM,N - substitution of the rows from m-th to n-th;
DM,N - deleting the rows from m-th to n-th;
E - end of editing;
where m and n are the number of rows in the file F.The commands are recorded one on row and are made as a menu.
This is the program. I researched a lot in the web about text editing and there are some text editing programs' source codes, but I guess I'm still in the beginning of programing and I find those source codes really difficult to understand. I'm concerned about few things:
Must I manually put text in the text file F and must I add another option in the menu about adding text;
The other thing is about the commands - how do I find and use the different rows from the text so I can insert, substitute and delete rows;
Well that is all. If you have the time please help me, because I really need to know how this program must be done in a not so complicated way and I think it got some valuable things that I could learn from it. Thanks in advance !
In pseudo-code, you ll find every real function you ll need in the documpentation.:
You ll need to write parse() yourself, all vec.something and input.something are real vector or string function, under a different name, you ll need to search the documentation.
open, close and writeinfile are io function under different name too (and different parameters), again, see the doc
getuserinput is also a renamed basic io function.
The reason I write this is to give you an idea of how to do this, it is not the solution spoon feeded to you, think of it as the algorithm, if you can do your homework without it, it is far better than using it. Also, learn to search the doc, it is really useful
vector<string> vec
int n, m
string input, output
//Open the file
open(your_file)
//Store every line in a string in the vector
while(input != EOF)
{
input = getalinefrom(file)
vec.add(input)
}
//You don t need the file for now, so close it
close(file)
//Create your 'menu', presuming text based, if graphical, well...
do
{
//Get user choice
input = getuserinput()
//Every command is just a letter, so check it to know what to do
if(input.firstchar == 'A')
{
//Parse the input to get n
n = parse(input)
//Get the line to add
input = getuserinput()
//Add it before n
vec.addafter(n, input)
}
else if (input.firstchar == 'I')
{
//Parse the input to get n
n = parse(input)
//Get the line to add
input = getuserinput()
//Add it before n
vec.addbefore(n, input)
}
else if (input.firstchar == 'C')
{
//Well, I don t see what is substitution so I ll let you try
}
else if (input.firstchar == 'D')
{
//Get n and m
n = parse(input)
m = parse(input)
//Presuming n < m, you ll need to check for error
while(n < m)
{
vec.deleterow(n)
n = n + 1
}
}
//Go out of the loop at E since it s the end of the app
}while(input != "E");
//Concatene every line
n = 0
do
{
output = output + vec.contentofrow(n)
}while(n < vec.length)
//Open the file again, with correct flag it will erase it content
open(file)
//Write your new content
writeinfile(file, output)
//Close the file
close(file)
return 0;

Skip last K lines while traversing a file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
A user had posted a similar question earlier this day which was very soon closed due to its vagueness. Thus re-posting the question in detail with a solution as I didn't find a specific article dealing with it on the internet.
The requirement is to read and print all lines of a file except the last K.
Suppose a file contains text as:
Hello there!
My name is
Mr. XYZ
I like playing football
And if K is 2, then it should print all the lines except the last 2. i.e.:
Hello there!
My name is
Why not simply put lines into a std::deque and dump one element when its size is greater k ?
#include<iostream>
#include<fstream>
#include<deque>
int main()
{
std::fstream fs;
fs.open("output.txt",std::ios::in);
std::deque<std::string> deq;
std::string str;
int k=2;
while(std::getline(fs,str))
{
deq.push_back(str);
if(deq.size() > k)
{
std::cout <<deq.front()<<std::endl;
deq.pop_front();
}
}
}
This can easily be solved by creating a window of size K and then traversing the file till the right end of the window reaches the end of the file. The basic steps being:
Traverse the first K lines of the file without printing it.
Open the same file using another stream object.
Now simultaneously traverse both the streams so that fisrt stream is always K lines ahead of the second stream.
Run a loop while the second first stream is valid. In the loop, read through the first stream as well and keep print the lines.
The code would be
#include<iostream>
#include<fstream>
#include<string>
int main()
{
fstream fs;
fs.open("abc.txt",ios::in);
string str;
int K = 2;
while(getline(fs,str) && K>1)
{
K--;
}
if(K==1)
{
fstream fsNew;
fsNew.open("abc.txt",ios::in);
while(getline(fs,str))
{
getline(fsNew,str);
cout<<str;
}
}
cin.ignore();
}