I have a text file where I need to be able to add or delete certain lines using functions. Everything is read from the file so when I open the file and write something then it deletes everything else in that file. I've understood that this can be done by using vectors. As I am new to C++ and especially vectors, I haven't figured out how I can read every line to a vector and then rewrite the lines to the text file.
Maybe someone can recommend me some kind of web-page or sth where I could learn how to do it.
Function for adding a line so far but it does not add the new line.
It should read the existing lines in the text file to vector<string> lines and then output it to the file while ignoring the first line with lines[i+1] and then add the new contact info to the end outside of the for loop.
void add contact(string filename, string*& names, string*& emails,
string*& numbers, unsigned int& quantity, string name, string email,
string number){
string str;
vector<string> lines;
ifstream input(filename);
while(getline(input, str)){
lines.push_back(str);
}
input.close();
ofstream output("contacts.txt");
output << quantity;
for(unsigned int i = 0; i < quantity; i++){
output << endl << lines[i+1];
}
output << endl << name << " | " << email << " | " << number << endl;
}
It's not that tough. You just have to get each line and push it to the std::vector.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main()
{
std::string str ;
std::vector<std::string> file_contents ;
std::fstream file;
file.open("test.txt",std::ios::in);
while(getline(file, str))
{
file_contents.push_back(str) ;
}
// You can access it using vector[i]
}
Related
Im doing a login/registration system and the thing Im struggling with is checking whether the password is correct. So I have a text file with the user data that looks like this.
email: email#email.com
username: user123
password: 1234
In order to check if the password given by the user is correct I need to compare it to the one in the file. So how do I extract the password from the *.txt file. I really have no idea where to start.
You could take a look at this answer I found:
Reading file line by line
I think this can be a good start!
Then you can try to keep just the password: Get substring after specific character
Reading a configuration file like that is something useful that you will quickly benefit from. Usually it is a pretty standard code where you iterate through all the lines of your file, reading key-value pairs and storing them (for example, in a std::map<std::string, std::string>), to use them later.
Here you have a commented example of how such code would be:
#include <fstream> // ifstream
#include <sstream> // stringstream
#include <iostream> // cout, endl
#include <iomanip> // ws
#include <map> // map
using namespace std;
int main(){
map<string, string> configuration;
ifstream fin("your_file.txt");
string line;
while(getline(fin, line)){ // loop through every line in the file
string key;
string value;
stringstream ss(line); // make a stream from the line
getline(ss, key, ':'); // read key until :
ss >> ws; // ignore whitespaces
getline(ss, value); // read value until newline
// Store them
configuration[key] = value;
}
cout << "PW: " << configuration["password"] << endl;
return 0;
}
If the words "email" "username" and "password" are written in the text document, start by removing them so it looks like this.
email#email.com
user123
1234
Then if you put the text file in the same folder as the source, this basic program should be a start.
#include <iostream>
#include <fstream>
#include <string>
using std::cout;
using std::cin;
using std::ifstream;
using std::getline;
using std::endl;
using std::string;
int main()
{
ifstream input("info.txt"); //open the text document
string line;
//int lineCounter;
string mail;
string password;
string username;
cout << "Enter your mail: " << endl;
cin >> mail;
cout << "Enter your password: " << endl;
cin >> password;
int compareResult;
if (input.is_open())
{
while(getline (input,line)) //loop through input file line by line
{
if (line.length() > 0) //skip empty lines
{
//lineCounter++; //keeps track of what line you're at
compareResult = line.compare(mail); //compare each line of the document with the entered mail
if (compareResult == 0) //if match..
{
getline (input,line); //get next line (username)
username = line; //store username in a variable
getline (input,line); //get next line (password)
compareResult = line.compare(password); //compare password with entered password
if (compareResult == 0) //if match..
{
cout << "Logged in as " << username << endl;
}
}
}
}
input.close();
}
return 0;
}
Just change the code to match the name of your textfile or vice versa, just tried it and got logged in as user123.
Next time you need to find the answer to something similar, search for something like "searching text file for a particular string c++"
I haven't done anything in c++ in ages, but this question was the first I saw after signing up so I felt compelled,
THANK YOU!
I am trying to read a database file (as txt) where I want to skip empty lines and skip the column header line within the file and store each record as an array. I would like to take stop_id and find the stop_name appropriately. i.e.
If i say give me stop 17, the program will get "Jackson & Kolmar".
The file format is as follows:
17,17,"Jackson & Kolmar","Jackson & Kolmar, Eastbound, Southeast Corner",41.87685748,-87.73934698,0,,1
18,18,"Jackson & Kilbourn","Jackson & Kilbourn, Eastbound, Southeast Corner",41.87688572,-87.73761421,0,,1
19,19,"Jackson & Kostner","Jackson & Kostner, Eastbound, Southeast Corner",41.87691497,-87.73515882,0,,1
So far I am able to get the stop_id values but now I want to get the stop name values and am fairly new to c++ string manipulation
mycode.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string filename;
filename = "test.txt";
string data;
ifstream infile(filename.c_str());
while(!infile.eof())
{
getline(infile,line);
int comma = line.find(",");
data = line.substr(0,comma);
cout << "Line " << count << " "<< "is "<< data << endl;
count++;
}
infile.close();
string sent = "i,am,the,champion";
return 0;
}
You can use string::find 3 times to search for the third occurrence of the comma, and you must store the positions of the last 2 occurrences found in line, then use them as input data with string::substr and get the searched text:
std::string line ("17,17,\"Jackson & Kolmar\",\"Jackson & Kolmar, Eastbound, Southeast Corner\",41.87685748,-87.73934698,0,,1");
std::size_t found=0, foundBack;
int i;
for(i=0;i<3 && found!=std::string::npos;i++){
foundBack = found;
found=line.find(",",found+1);
}
std::cout << line.substr(foundBack+1,found-foundBack-1) << std::endl;
You can read the whole line of the file intoa string and then use stringstream to give you each piece one at a time up until and exluding the commas. Then you can fill up your arrays. I am assuming that you wanted each line in it's own array and that you wanted unlimited arrays. The best way to do that is to have an array of arrays.
std::string Line;
std::array<std::array<string>> Data;
while (std::getline(infile, Line))
{
std::stringstream ss;
ss << Line;
Data.push_back(std::vector<std::string>);
std::string Temp;
while (std::getline(ss, Temp, ','))
{
Data[Data.size() - 1].push_back(Temp);
}
}
This way you will have a vector, full of vectors, each of which conatining strings of all your data in that line. To access the strings as numbers, you can use std::stoi(std::string) which converts a string to an integer.
I asked a question yesterday but i didn't manage to do anything. I am using visual studio with marmalade and im already studying c++ but i need to get things done here so i asking for i little help and patience of you guys.
I got a few responses like
std::ifstream inp("restrict_words.txt");
std::istream_iterator<std::string> inp_it(inp), inp_eof;
std::vector<std::string> words(inp_it, inp_eof);
// words now has ever whitespace separated string
// from the input file as a vector entry
for (auto s : words)
std::cout << s << '\n';
and
std::ifstream ist("restrict_words.txt");
std::string word;
std::vector<std::string> readWords;
while(ist >> word)
readWords.push_back(word);
//test
for(unsigned i = 0; i != readWords.size(); ++i)
std::cout << readWords.at(i) << '\n';
Its such a easy thing and im not managing to do this.
I have my KingChatFilter.app and a chat folder inside my game folder. Inside this chat folder i have this txt with 160 words in 160 different lines.
All i need to do is read this txt and after putting it on a array checking if some of this string match with the one i want so i can do other stuff.
Please someone make me understand this thanks :)
I wrote a couple of functions to match your requirements:
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;
// Reads the file line by line and put all lines into words vector.
void read_to_vector(const char* file_name, vector<string> &words)
{
ifstream input(file_name);
string line;
while (getline(input, line))
{
words.push_back(line);
}
}
// Returns true if word is in words. False otherwise.
bool find_word(vector<string> &words, string word)
{
vector<string>::iterator it; // In c++11 you can change this to
// auto it;
// Using std::find from algorithm library.
it = find(words.begin(), words.end(), word);
return it != words.end(); // If the end of vector words was reached, then word was NOT found.
}
int main()
{
vector<string> words;
string target = "level";
read_to_vector("data.txt", words);
if (find_word(words, target))
cout << "Word " << target << " found" << endl;
else
cout << "Word " << target << " not found" << endl;
return 0;
}
following is working code i used to read file content line by line. One difference is maybe that u do not check if opening the file did succeed. If it does not, there come at least two main reasons to mind:
the file cannot be found at the specified path
the file is already opened by someone else
;
std::string fileNameWithPath = "..\\myFolder\\myfile.txt";
std::ifstream inputFile;
std::vector< std::string > fileContent;
inputFile.open( fileNameWithPath.c_str(), std::ios::in | std::ios::binary );
if( inputFile.is_open() )
{
std::string line;
while( std::getline( testDataFile, line ) )
{
inputFile.push_back( line );
}
}
inputFile.close();
I'm in a tutorial which introduces files (how to read from file and write to file)
First of all, this is not a homework, this is just general help I'm seeking.
I know how to read one word at a time, but I don't know how to read one line at a time, or how to read the whole text file.
What if my file contains 1000 words? It is not practical to read entire file word after word.
My text file named "Read" contains the following:
I love to play games
I love reading
I have 2 books
This is what I have accomplished so far:
#include <iostream>
#include <fstream>
using namespace std;
int main (){
ifstream inFile;
inFile.open("Read.txt");
inFile >>
Is there any possible way to read the whole file at once, instead of reading each line or each word separately?
You can use std::getline :
#include <fstream>
#include <string>
int main()
{
std::ifstream file("Read.txt");
std::string str;
while (std::getline(file, str))
{
// Process str
}
}
Also note that it's better you just construct the file stream with the file names in it's constructor rather than explicitly opening (same goes for closing, just let the destructor do the work).
Further documentation about std::string::getline() can be read at CPP Reference.
Probably the easiest way to read a whole text file is just to concatenate those retrieved lines.
std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
file_contents += str;
file_contents.push_back('\n');
}
I know this is a really really old thread but I'd like to also point out another way which is actually really simple... This is some sample code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("filename.txt");
string content;
while(file >> content) {
cout << content << ' ';
}
return 0;
}
I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.
Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
freopen("path to file", "rb", stdin);
string line;
while(getline(cin, line))
cout << line << endl;
return 0;
}
The above solutions are great, but there is a better solution to "read a file at once":
fstream f(filename);
stringstream iss;
iss << f.rdbuf();
string entireFile = iss.str();
you can also use this to read all the lines in the file one by one then print i
#include <iostream>
#include <fstream>
using namespace std;
bool check_file_is_empty ( ifstream& file){
return file.peek() == EOF ;
}
int main (){
string text[256];
int lineno ;
ifstream file("text.txt");
int num = 0;
while (!check_file_is_empty(file))
{
getline(file , text[num]);
num++;
}
for (int i = 0; i < num ; i++)
{
cout << "\nthis is the text in " << "line " << i+1 << " :: " << text[i] << endl ;
}
system("pause");
return 0;
}
hope this could help you :)
hello bro this is a way to read the string in the exact line using this code
hope this could help you !
#include <iostream>
#include <fstream>
using namespace std;
int main (){
string text[1];
int lineno ;
ifstream file("text.txt");
cout << "tell me which line of the file you want : " ;
cin >> lineno ;
for (int i = 0; i < lineno ; i++)
{
getline(file , text[0]);
}
cout << "\nthis is the text in which line you want befor :: " << text[0] << endl ;
system("pause");
return 0;
}
Good luck !
Another method that has not been mentioned yet is std::vector.
std::vector<std::string> line;
while(file >> mystr)
{
line.push_back(mystr);
}
Then you can simply iterate over the vector and modify/extract what you need/
The below snippet will help you to read files which consists of unicode characters
CString plainText="";
errno_t errCode = _tfopen_s(&fStream, FileLoc, _T("r, ccs=UNICODE"));
if (0 == errCode)
{
CStdioFile File(fStream);
CString Line;
while (File.ReadString(Line))
{
plainText += Line;
}
}
fflush(fStream);
fclose(fStream);
you should always close the file pointer after you read, otherwise it will leads to error
I need to read a .dat file which looks like this:
Atask1 Atask2 Atask3 Atask4 Atask5
Btask1 Btask2 Btask3 Btask4 Btask5
Ctask1 Ctask2 Ctask3 Ctask4 Ctask5
Dtask1 Dtask2 Dtask3 Dtask4 Dtask5
and i need to be able to output information like this:
cout << line(3) << endl; // required output shown below
>>Ctask1 Ctask2 Ctask3 Ctask4 Ctask5
cout << line(2)(4) << endl; // required output shown below
>>Btask4
I don't know how to read 1 line and split it into an array of 5 different strings.
I'd ideally like to have the whole .dat file converted into a vector or a list or some kind of matrix/array structure for easy reference
any simple code or solutions for this??
PLEASE HELP?!?!?!? :-)
EDIT:
vector<string> dutyVec[5];
dut1.open(dutyFILE);
if( !dut1.is_open() ){
cout << "Can't open file " << dutyFILE << endl;
exit(1);
}
if(dut1.eof()){
cout << "Empty file - no duties" << endl;
exit(1);
}
while ( !dut1.eof()){
int count = 0;
getline(dut1, dutyVec[count]);
count++;
}
Your problem addresses a number of issues, all of which I will attempt to answer in one go. So, forgive the length of this post.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <fstream>
int main(int argc, char argv[]){
std::vector <std::string> v;//just a temporary string vector to store each line
std::ifstream ifile;
ifile.open("C://sample.txt");//this is the location of your text file (windows)
//check to see that the file was opened correctly
if(ifile.is_open()) {
//while the end of file character has not been read, do the following:
while(!ifile.eof()) {
std::string temp;//just a temporary string
getline(ifile, temp);//this gets all the text up to the newline character
v.push_back(temp);//add the line to the temporary string vector
}
ifile.close();//close the file
}
//this is the vector that will contain all the tokens that
//can be accessed via tokens[line-number][[position-number]
std::vector < std::vector<std::string> > tokens(v.size());//initialize it to be the size of the temporary string vector
//iterate over the tokens vector and fill it with data
for (int i=0; i<v.size(); i++) {
//tokenize the string here:
//by using an input stringstream
//see here: http://stackoverflow.com/questions/5167625/splitting-a-c-stdstring-using-tokens-e-g
std::istringstream f(v[i].c_str());
std::string temp;
while(std::getline(f, temp, ' ')) {
tokens[i].push_back(temp);//now tokens is completely filled with all the information from the file
}
}
//at this point, the tokens vector has been filled with the information
//now you can actually use it like you wanted:
//tokens[line-number][[position-number]
//let's test it below:
//let's see that the information is correct
for (int i=0; i<tokens.size(); i++) {
for(int j=0; j<tokens[i].size(); j++) {
std::cout << tokens[i][j] << ' ';
}
std::cout << std::endl;
}
system("pause");//only true if you use windows. (shudder)
return 0;
}
Note, I did not use iterators, which would have been beneficial here. But, that's something I think you can attempt for yourself.