C++ dealing with files - c++

I have a problem working in C++ with txt files.. First of all, I want to make a program which
have .cpp and .h files.. which have classes and functions.
So here is my problem:
for example, i have txt file which contains 5 lines of text (players names). So I want to make every line of that txt to be a variable of string.. But as long as I want to use that new variables they suddently disappears.
Here is program code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
int i;
string player[5];
ifstream myfile ("1-Efes Pilsen.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
for (i=0;i<5;i++)
{
getline (myfile,line);
player[i] = line;
}
// after this point I still can use new variables
}
}
else cout << "Unable to open file";
cout << player[1]; // <--- NOT WORKING. WHY?
myfile.close();
}

While it is not clear to me how it's not working, I can guess that there are more contents in the file than just 5 strings (perhaps another newline) which causes the while condition to evaluate to true causing the for loop to read 5 lines (which will fail and not actually read anything) and replace the good values in the string array with crappy ones (empty string).
Instead of having an outer while loop, you probably want to add the condition to the for loop itself; something along the lines of:
for (i=0;i<5 && myfile.good();i++)
{
getline (myfile,line);
player[i] = line;
}

Related

How can I read from a file and sort them by category

I'm trying to read a bunch of words from a file and sort them into what kind of words they are (Nouns, Adjective, Verbs ..etc). For example :
-Nouns;
zyrian
zymurgy
zymosis
zymometer
zymolysis
-Verbs_participle;
zoom in
zoom along
zoom
zonk out
zone
I'm using getline to read until the delimiter ';' but how can I know when it read in a type and when it read in a word?
The function below stop right after "-Nouns;"
int main()
{
map<string,string> data_base;
ifstream source ;
source.open("partitioned_data.txt");
char type [MAX];
char word [MAX];
if(source) //check to make sure we have opened the file
{
source.getline(type,MAX,';');
while( source && !source.eof())//make sure we're not at the end of file
{
source.getline(word,MAX);
cout<<type<<endl;
cout<<word<<endl;
source.getline(type,MAX,';');//read the next line
}
}
source.close();
source.clear();
return 0;
}
I am not fully sure about the format of your input file. But you seem to have a file with lines, and in that, items separated by a semicolon.
Reading this should be done differently.
Please see the following example:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
std::istringstream source{R"(noun;tree
noun;house
verb;build
verb;plant
)"};
int main()
{
std::string type{};
std::string word{};
//ifstream source{"partitioned_data.txt"};
if(source) //check to make sure we have opened the file
{
std::string line{};
while(getline(source,line))//make sure we're not at the end of file
{
size_t pos = line.find(';');
if (pos != std::string::npos) {
type = line.substr(0,pos);
word = line.substr(pos+1);
}
std::cout << type << " --> " << word << '\n';
}
}
return 0;
}
There is no need for open and close statements. The constructor and
destructor of the std::ifstream will do that for us.
Do not check eof in while statement
Do not, and never ever use C-Style arrays like char type [MAX];
Read a line in the while statement and check validity of operation in the while. Then work on the read line later.
Search the ';' in the string, and if found, take out the substrings.
If I would knwo the format of the input file, then I will write an even better example for you.
Since I do not have files on SO, I uses a std::istringstream instead. But there is NO difference compared to a file. Simply delete the std::istringstream and uncomment teh ifstream definition in the source code.

Code to print out number of lines and integer values

I created a data file called program.txt. I need to create code that prints out number of lines and integer values from that program.txt
Heres the text I made
1
35
45
87
9
100
the program.text has these values in it
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string calc;
int test;
int cool;
int book;
ifstream myfile;
ifstream outof;
myfile.open ("program.txt");
outof.open("program.txt");
if (myfile.fail())
{
cerr<<"Error Opening file"<<endl;
}
if(outof.fail ())
{
cerr<<"Error Opening file"<<endl;
}
while (!myfile.eof ())
{
getline(myfile,calc);
++book;
}
cout <<book<<endl;
while (!outof.eof ())
{
outof<<test;//
cool++;
}
cout<<cool<<endl;
myfile.close();
outof.close();
}
Also after cerr I tried exit (1) and it said exit was not defined.
I am new to this any help would be greatly appreciated. Thanks This is C++ btw.
The problem is that you are using ifstream, which stands for INPUT file stream. You want to use ofstream, which is OUTPUT file stream. You cannot write to an input file stream, hence why the << operator is not defined.
Also, rather than using exit(1) after your errors, you can just return 1; as you are inside your main function. This will terminate the program, returning 1 as the exit code.
If you really want to use exit, you need to #include <cstdlib>.
Your defined input and expected output aren't clearly defined, so I'm not sure what you're trying to do. However, here's a general idea:
Putting the filename in a fstream's constructor will automatically try to open the file for read/write. You dont need to call .open() anymore. Also, you shouldnt be reading and writing to the same file simultaneously if you dont know what you're doing.
std::ifstream myInputFile("program.txt");
std::ofstream myOutputFile("programOut.txt");
Rather than checking myInputFile.fail(), just use the overloaded boolean operator. In depth explanation: ifstream::is_open vs ifstream::fail?
if (!myInputFile) {
//Something went wrong
std::cerr << "Failed to open input file" << std::endl;
return 1;
}
Define your std::string to hold lines as you read them, read all of your input file, and count the lines.
std::string line;
int lineCount = 0;
while (getline(myInputFile,line)) {
++lineCount;
//Do something with 'line'
}
Maybe you'll need to store the lines from your input file so that you can output the count of the lines at the beginning of your output file, you might want to #include <vector> and do something like this:
std::string line;
std::vector<std::string> linesFromFile;
//Read in all lines of the input file and store them in the vector
while (getline(myInputFile, line)) {
linesFromFile.emplace_back(line);
}
//All lines read, good time to close input file
myInputFile.close();
//Print number of lines read
myOutputFile << linesFromFile.size() << std::endl;
//Loop through lines and print them
for (auto &lineFromFile : linesFromFile) {
myOutputFile << lineFromFile << std::endl;
}
//Done outputting, close output file
myOutputFile.close();

read word to file c++

I want get from user word and put into place in file where is certian word.
I have problem with getline.
In new file I don't have any new line.
When I add Newline to string which I write to file, this line is read two times and writeto file to times (I think that bcoz I saw this newfile)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string contain_of_file,bufor,word,empty=" ",new_line="\n";
string conection;
string::size_type position;
cout<<"Give a word";
cin>>word;
ifstream NewFile;
ofstream Nowy1;
Nowy1.open("tekstpa.txt", ios::app);
NewFile.open("plik1.txt");
while(NewFile.good())
{
getline(NewFile, contain_of_file);
cout<<contain_of_file;
position=contain_of_file.find("Zuzia");
if(position!=string::npos)
{
conection=contain_of_file+empty+word+new_line;
Nowy1<<conection;
}
Nowy1<<contain_of_file;
}
Nowy1.close();
NewFile.close();
cin.get();
return 0;
}
The problem here is not your reading. directly, but about your loop.
Do not loop while (stream.good()) or while (!stream.eof()). This is because the eofbit flag is not set until after you try to read from beyond the file. This means that the loop will iterate one extra time, and you try to read from the file but the std::getline call will fails but you don't notice it and just continue as if nothing happened.
Instead do
while (std::getline(NewFile, contain_of_file)) { ... }
And an unrelated tip: The variable conection is not needed, you can instead do just
Nowy1 << contain_of_file << ' ' << word << '\n';

Reading from .txt

I'm trying to solve Problem 13 of project euler, which involves the sum of 100 50 digit numbers. I figured there would be a better way than the paste that whole chunk of numbers into my code. So I searched around and found that you could paste the chunk into a .txt file and read it from there.
So, how would I go about reading from a .txt file in C++ and more importantly getting the 50 digit strings individually from it?
Something like this?
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("numbers.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
int i = atoi(line.c_str());
// do here something with 'i'
cout << i
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}

seekg tellg end of line

I have to read lines from an extern text file and need the 1. character of some lines.
Is there a function, which can tell me, in which line the pointer is and an other function, which can set the pointer to the begin of line x?
I have to jump to lines before and after the current position.
There is no such function i think. You will have to implement this functionality yourself using getline() probably, or scan the file for endline characters (\n) one character at a time and store just the one character after this one.
You may find a vector (vector<size_t> probably) helpful to store the offsets of line starts, this way you might be able to jump in the file in a line-based way. But haven't tried this, so it may not work.
You may ake a look at ifstream to read your file in a stream, then use getline() to get each line in a std::string.
Doing so, you can easily iterate trough the lines and grab the characters you need.
Here is an example (taken from here):
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl; // Here instead of displaying the string
// you probably want to get the first character, aka. line[0]
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}