I have a problem with reading from a file - c++

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
fstream file, save_file;
vector<string> words;
for (int i = 0; i < 1000; i++)
file >> words[i];
cout << words[0];
return 0;
}
I want to save these words in a vector, but I can't. I have a message: zad1.exe is already runing! Please close it first to compile successfully! I don;t know why.

Here is my solution:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main()
{
std::fstream file("test.txt"), save_file;
std::vector<std::string> words;
std::string line;
for (int i = 0; i < 1000; i++){
file >> line;
words.push_back(line);
}
std::cout << words[0];
return 0;
}
Instead of test.txt write your file path

On some operating systems you cannot write to a file if that file is a running program. That is what the error message is telling you. You are creating a program called zad1.exe and it is currently running so you cannot create a new version of zad1.exe until you stop the version that is already running.
Are you working on Windows? If so then use the task manager to kill any versions of zad1.exe that you can see.
Plus you have many problems with the code as pointed out in the comments above. But the first task is to kill those running programs.

Related

How to store a text file into a vector (C++) [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 5 years ago.
Improve this question
I need help storing text from a text file into a vector.
The text file is called "names.txt" and it has the following data
salman
mahmoud
ahmad
ghadeer
raghad
abdullah
faisal
The text below is my code
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main ()
{
vector<string> STRING;
ifstream infile;
infile.open ("names.txt");
for(size_t i = 0; i < 7; i++)
{
getline (infile, STRING[i]);
cout << STRING[i];
}
infile.close();
return 0;
}
Everytime I run the program, I get the following error message
You declared your vector, but you did not set its size.
You can:
Either declare a vector with a specific size
or simply use push_back() function like below:
.
for(size_t i = 0; i < 7; i++)
{
string temp; // temporal variable - just a place holder
getline (infile, temp); // get line
MyVector.push_back(temp); // add it to the vector (add to the end of it)
}
You are trying to access elements of the vector which are not created.
When you call
vector<string> STRING
it creates a vector capable of storing strings, but not having any.
So, when you a trying to access one of them with STRING[i], it says that you are trying to access non-existing element.
Possible solution: before the loop call
STRING.resize(7);
It'll allocate memory for 7 empty strings and then this loop will work just fine.
You can try this way :
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main ()
{
vector<string> STR;
ifstream infile;
infile.open ("names.txt");
for(size_t i = 0; i < 7; i++)
{
string st;
getline (infile, st);
STR.push_back(st);
cout << STR[i] << endl;
}
infile.close();
return 0;
}
Your problem is that you are trying to write to an empty vector. This can easily be fixed by simply change:
vector<string> STRING;
to:
vector<string> STRING(7);
However, you should change the name of the vector to something like:
vector<string> lines;
One last thing (less important) is the fact that you read 7 lines from the file. What if the file has 4 lines or maybe 56 lines? So, here's what you should really do:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main () {
std::vector<std::string> lines;
std::ifstream infile("names.txt");
std::string line;
while(std::getline(infile, line)) {
lines.push_back(line);
std::cout << lines.back() << std::endl;
}
return 0;
}

Copying a file with streams in C++

I wrote this in an attempt to copy the contents of one text file into another based on command-line arguments:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
if(argc != 3) {
cout << "invalid args!";
return 0;
}
fstream op(argv[1], ios::in);
vector<string> list;
string line;
while(!op.end)
op >> line;
list.push_back(line);
op.close();
op.open(argv[2], ios::out);
for(unsigned int i = 0; i < list.size(); i++)
op << list[i];
op.close();
return 0;
}
It does not produce any syntax errors, but a logic error is evident: there is no output.
So apart from the lack of error-checking and the fact that there are more efficient ways to do this, what is wrong with my code? That is, why will it not copy file with name argv[1] to a file named argv[2]?
You have a bug: your while loop's body is not enclosed in {}, so only op >> line is executed until the file is read completely, and the last value of line is then pushed onto the vector.
EDIT: By the way, that's a very good illustration for why you should let your editor do your code indentation; the way your while loop looked, it was hard to spot this mistake.
There are several issues in your code:
With streams you shall not loop on end or eof (have a look at the many SO questions/answers about this).
The enclosing {} issue that Marcus revealed
You are not reading lines but words (operator>> uses spaces as separators) and squizing the whitespaces in the output.
Here how to tackle all this:
while(getline(op, line))
list.push_back(line);
and of course for the output: op << list[i]<<endl;
For one-to-one copy, you may also consider the following code - handles binary data, uses less memory and is shorter:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
using namespace std;
int main(int argc, char *argv[])
{
if (argc < 3)
return 1;
fstream s(argv[1], ios::in);
fstream d(argv[2], ios::out);
copy(
istreambuf_iterator<char>(s)
, istreambuf_iterator<char>()
, ostreambuf_iterator<char>(d));
return 0;
}

Cannot Output Data Into a Text File

I am experimenting with some code for outputting information to a file. The file address appears to be correct and the code compiles but the file never populates. Can you see a problem?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int size = 10;
for(int i=0; i<size; ++i)
{
ofstream outputfile;
outputfile.open("C:MyFolder\outputfile.txt", ios::app);
outputfile << "SYMBOL, STOCK_PRICE" << endl;
outputfile << i << endl;
outputfile.close();
}
}
When fixing the path to be an actual Windows path, it runs ok for me;
outputfile.open("C:\\MyFolder\\outputfile.txt", ios::app);
maybe the path is not right, you did not escape the backslashes. otherwise the code is fine, and worked for me.
Others have given answer to your problem. I also suggest you to open and close file only once (outside loop), and do only file-writing within loop.

How can I do file i/o without fstream for competitions like google code jam?

Let me preface this question by saying I am not a very experienced programmer.
For competitions like google code jam, I write code like this:
#include <fstream>
using namespace std;
int main() {
ifstream fin("file.in");
ofstream oin("file.out");
//Etc. I'll now write out my solution.
//...
}
However, I noticed that many other code sources by other participants don't use fstream at all and use iostream instead. Then they'll use cout and cin as if they were reading and writing from the console.
How are they doing this? Can I do the same thing if I am using g++ and ubuntu?
EDIT: Since it was requested that I post an example of what I mean, here is code from participant ryuuga who solved large Bot Trust, Problem A from the recent '11 qualification round.
He uses cin and cout but I don't know how he is doing file i/o.
#include <iostream>
using namespace std;
#include <cstdio>
#include <algorithm>
#include <deque>
#include <map>
#include <set>
typedef pair<int,int> pii;
#include <vector>
typedef vector<int> vi;
#include <queue>
#include <stack>
#define For(i,a,b) for(int i=(a);i<(b);++i)
#define ForI(i,a,b) for(int i=(a);i<=(b);++i)
#define ForAll(it,set) for(typeof(set.begin()) it = set.begin(); it!=set.end(); ++it)
typedef stack<int> si;
typedef queue<int> qi;
int main(){
int t;
cin>>t;
ForI(tt,1,t){
int n;cin>>n;
int pos[2]={1,1}, time[2] = {0,0};
int curTime = 0;
For(i,0,n){
char type; int button;
cin>>type>>button;
type = (type=='B'?1:0);
int nextTime = 1+max(curTime, time[type] + abs(button - pos[type]));
pos[type] = button;
time[type] = nextTime;
curTime = nextTime;
}
cout<<"Case #"<<tt<<": "<<curTime<<endl;
}
return 0;
}
Imagine when you are using the shell in ubuntu. Almost everything is read by the console, cin and written to the console, cout. For instance
cat "file.txt" | grep "Hello"
cat would get the "file.txt" from the arguments given to main, i.e.
main(int argc, char ** argv){
// for the both cat and grep examples argc is 2
// argv[1] contains "file.txt" for cat.
// open an ifstream and ouput it to cout. There's cat for you.
}
To find out what argv[0] contains, try it out!
grep would read the same argument then read everything from cin, copy the input that matches argv[1] to cout
EDIT: He is running his program with
cat "downloaded-input-file.txt" | theprogram > output.txt
Then submits the program. Or he might be using the < downloaded-input-file syntax. I'm keeping the initial explanation as it might be useful for the understanding of the process.

Most Compact Way to Count Number of Lines in a File in C++

What's the most compact way to compute the number of lines of a file?
I need this information to create/initialize a matrix data structure.
Later I have to go through the file again and store the information inside a matrix.
Update: Based on Dave Gamble's. But why this doesn't compile?
Note that the file could be very large. So I try to avoid using container
to save memory.
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
int main ( int arg_count, char *arg_vec[] ) {
if (arg_count !=2 ) {
cerr << "expected one argument" << endl;
return EXIT_FAILURE;
}
string line;
ifstream myfile (arg_vec[1]);
FILE *f=fopen(myfile,"rb");
int c=0,b;
while ((b=fgetc(f))!=EOF) c+=(b==10)?1:0;
fseek(f,0,SEEK_SET);
return 0;
}
I think this might do it...
std::ifstream file(f);
int n = std::count(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), '\n') + 1;
If the reason you need to "go back again" is because you cannot continue without the size, try re-ordering your setup.
That is, read through the file, storing each line in a std::vector<string> or something. Then you have the size, along with the lines in the file:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main(void)
{
std::fstream file("main.cpp");
std::vector<std::string> fileData;
// read in each line
std::string dummy;
while (getline(file, dummy))
{
fileData.push_back(dummy);
}
// and size is available, along with the file
// being in memory (faster than hard drive)
size_t fileLines = fileData.size();
std::cout << "Number of lines: " << fileLines << std::endl;
}
Here is a solution without the container:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main(void)
{
std::fstream file("main.cpp");
size_t fileLines = 0;
// read in each line
std::string dummy;
while (getline(file, dummy))
{
++fileLines;
}
std::cout << "Number of lines: " << fileLines << std::endl;
}
Though I doubt that's the most efficient way. The benefit of this method was the ability to store the lines in memory as you went.
FILE *f=fopen(filename,"rb");
int c=0,b;while ((b=fgetc(f))!=EOF) c+=(b==10)?1:0;fseek(f,0,SEEK_SET);
Answer in c.
That kind of compact?
#include <stdlib.h>
int main(void) { system("wc -l plainfile.txt"); }
Count the number of instances of '\n'. This works for *nix (\n) and DOS/Windows (\r\n) line endings, but not for old-skool Mac (System 9 or maybe before that), which used just \r. I've never seen a case come up with just \r as line endings, so I wouldn't worry about it unless you know it's going to be an issue.
Edit: If your input is not ASCII, then you could run into encoding problems as well. What's your input look like?