Issue in file operations in C++ [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
This is part of a c++ code that writes value of a vector of strings into a file.
int main () {
//freopen ("out.txt", "w+", stdout);
ofstream data;
data.open("data.txt");
BinaryTree<string>* bt = new BinaryTree<string>;
LoadBinaryTree(bt);
fillArrayOfNodes(bt);
for (int i = 0; drawArray[i] != "\0"; i++)
data << drawArray[i] << endl;
data.close();
delete bt;
return 0;
}
First, I couldn't write into the file. I mean after running the program and checking the output file, it was empty. after that, I noticed that my output format wasn't right. I changed it and now I can write into the file. (the code shown above is the modified code)

The problem is the way you're attempting to iterate through the array. The Standard C++ string class std::string should not be handled like a regular char array. That is, you shouldn't base your condition upon finding the null character. The correct way would be to iterate until you reach the length of the string.
Moreover, you should be using a vector of strings and inserting strings using push_back():
std::vector<std::string> v;
// fill vector with push_back()
for (int i = 0; i < v.size(); ++i)
data << v[i] << endl;

You need to include the right headers like <fstream>.
Try this example: http://www.cplusplus.com/doc/tutorial/files/

Related

is there something wrong with array.size? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
I want to give in a string into an array from keybord, so that i can count how many letters it has with for loop
I tried to buil and run the code but i doesnt work actually and there an error but I dont really understand the error and the way to fix them. The error is :
request for member size in Bao( my Array), which is of none class type
Here is my code:
char Bao[100];
cout<<"Give me a sentence"<<endl;
cin.getline(Bao, 100, '\n');
cout<< Bao.size()<<endl;
There is no function 'size' in a c++ array. You have to use
sizeof(array)
which gives the size of the array in bytes. To get the true size of the array use
sizeof(array)/sizeof(array[0])
which divides the size of the array with the size of a single element in the array giving you the number of elements.
Also, why are you using an array in this instance? It seems like a string might be what you are looking for.
Here, you shouldn't even be using an array. Use std::string.
Here's some sample code that accomplishes the same thing as the code you posted:
std::string sentence;
std::cout << "Give me a sentence" << std::endl;
std::cin.getline(sentence, 100, '\n');
std::cout << "Scentence is " << sentence.size() << " bytes" << std::endl;
EDIT: using getline() for the spacebar bug.

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.

Handling strings inside Files [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to save data from a file into an array but I've had no luck for now. It's easy to save data after it was read from the file in case it's just numbers, but for example if I'm trying to save strings, the program keeps crashing over and over again. I'm using fscanf(); function since the whole .txt file is written in the same format: "First Name, Last Name". Now then, I've tried using the for loop in this way:
char *firstName = (char*)malloc(sizeof(char)*10240);
char *lastName = (char*)malloc(sizeof(char)*10240);
for(int i = 0; i<10; i++){
fscanf(fp, "%s %s", firstName[i],lastName[i]);
}
And that's where it crashes.
Pure C code:
You have to allocate the array of arrays first, then allocate each string one by one
It's best to scan the strings into temp strings with a big size, and duplicate the strings later.
int i,nb_names = 10;
char **firstName = malloc(sizeof *firstName * nb_names);
char **lastName = malloc(sizeof *lastName *nb_names);
char tempn[1000],templ[1000];
for(i = 0; i<nb_names; i++){
fscanf(fp,"%s %s", tempn,templ);
firstName[i] = strdup(tempn);
lastName[i] = strdup(templ);
}
Note that I have changed for (int i to for (i because it is not C compliant but rather C++ compliant (or C99, not sure).
For C++, drop the mallocs and use std::vector and std:string instead.
I'd recommend to use C++ if you can. I answered a lot of C/C++ questions on people trying (and failing) to allocate 2D arrays properly (including me 5 minutes ago damn :)). C++ using C++ library code is much clearer.
Full C++ example, reading from standard input
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main()
{
int nb_names = 10;
vector<string > firstName(nb_names);
vector<string > lastName(nb_names);
for(int i = 0; i<nb_names; i++){
cin >> firstName[i];
cin >> lastName[i];
}
return 0;
}
The error in your code is : firstName[i] is a character not a string but you use it like a string by using %s instead of %c.
you should use a char ** instead of char *.
char **firstName = (char**)malloc(10*sizeof(char)*10240);
I think also that 10240 is too much for firstName. Use 255 or less.

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;
}

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();
}