Can't read/get text file(.txt) to vector, tried 3 approaches found on web (numbered 0-1-2). So far got number of words (distance algorithm), file size (didn't include code), but no vector. Please point me to mistake. Thank you.
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;
void intoVector (ifstream &stream, vector<string> &vector) {
string s;
getline (stream, s);
istringstream iss (s);
copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(vector));
}
int main(int argc, const char * argv[]) {
string s1="text.txt";
ifstream file (s1);
if (!file) {
cout<<"Couldn't find file"<<endl; exit(1);
}else {cout<<"File is found"<<endl;}
//words count - o.k.
istream_iterator<string> start(file), end;
cout<<"Word count: "<<distance(start, end)<<endl;//iterator distance - difference beteween 2 iterators, type ptrdiff_t
if (!file.is_open()) {
cout<<"File isn't open"<<endl;
}
//0)try
vector<string> vec1;
intoVector(file, vec1);
cout<<vec1.size()<<endl; //result- 0
//1) try1
vector<string> text1(start, end);
cout<<"Vector size "<<text1.size()<<endl; //result - 1, 1st word
copy(text1.begin(), text1.end(), ostream_iterator<string>(cout, " "));
//2)try2
vector<string> vec2;
string s2;
while (getline(file, s2)) {
vec2.push_back(s2);
}
cout<<"vec size "<<vec2.size()<<endl; //Result -0
}
All approached are working when I disable ifstream_iterator (distance algorithm). Previously had to make file size calculation as a function (outside main) 'cause it was conflicting with mentioned iterator
Related
I am attempting to write a program which can read in a text file, and store each word in it as an entry in a string type vector. I am sure that I am doing this very wrong, but it has been so long since I have tried to do this that I have forgotten how it is done. Any help is greatly appreciated. Thanks in advance.
Code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile;
vector<string>::iterator it;
it = input.begin();
readFile.open("input.txt");
for (it; ; it++)
{
char cWord[20];
string word;
word = readFile.get(*cWord, 20, '\n');
if (!readFile.eof())
{
input.push_back(word);
}
else
break;
}
cout << "Vector Size is now %d" << input.size();
return 0;
}
One of the many possible ways is a simple:
std::vector<std::string> words;
std::ifstream file("input.txt");
std::string word;
while (file >> word) {
words.push_back(word);
}
operator >> takes care of only words divided by whitespaces (including new-lines) being read.
And in case you would be reading it by lines, you might also need to explicitly handle empty lines:
std::vector<std::string> lines;
std::ifstream file("input.txt");
std::string line;
while ( std::getline(file, line) ) {
if ( !line.empty() )
lines.push_back(line);
}
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile("input.txt");
copy(istream_iterator<string>(readFile), {}, back_inserter(input));
cout << "Vector Size is now " << input.size();
}
Or, shorter:
int main()
{
ifstream readFile("input.txt");
cout << "Vector Size is now " << vector<string>(istream_iterator<string>(readFile), {}).size();
}
I'm not going to explain, because there's about a zillion explanations on StackOverflow already :)
I'm working on a program where the user will input in the format x,0,0 and it will be saved to a file then read into an array where I can compare the values however I'm stuck when trying to read into a 2D array can someone please help? Think the error is in the struct part
This is what I have so far:
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include <sstream>
using namespace std;
struct listArray
{
string name[];
int price1[];
int price2[];
};
int main()
{
listArray la;
string line;
cout << "Enter your list: ";
ofstream fout;
fout.open("list.txt");
while (fout) {
getline(cin, line);
if (line == "-1")
break;
fout << line << endl;
}
fout.close();
int count = 0;
ifstream listFile;
listFile.open("list.txt");
if(listFile.is_open()){
while (listFile) {
getline(listFile, la.name[count], ",");
count++;
listFile.close();
}
}
You can use delimiter to grab the substring, and use this substring to fill your struct, an exemple of split:
#include<iostream>
std::vector<std::string> split(const string& input, const string& regex)
{
// passing -1 as the submatch index parameter performs splitting
std::regex re(regex);
std::sregex_token_iterator first{input.begin(), input.end(), re, -1},last;
return {first, last};
}
if you are using C++11 or higher, you can use std::vector for arrays, and you also can use boost library, they have nice support for delimiter and other stuffs.
I have this .txt file that has a lot of words ( one each line ).
I tried
ifstream myReadFile;
myReadFile.open("restrict_words.txt");
char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
printf("mamao");
myReadFile >> output;
cout<<output;
}
}
But i dont know how to make it work like... where should i pass it path and stuff
I would like to do
while(reading){
stringArray.add(file.line);
}
How can i do that?
First, this: (!myReadFile.eof()) is wrong. See the link for why. Second. If all you want is to load a file of strings into an array, this will do it:
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
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';
}
Suggested reading:
std::vector<>
std::string
std::istream_iterator<>
C++11 Range-based for loop
Do you mean this?
//untested
#include <vector>
#include <fstream>
#include <string>
#include <iostream> //edited
int main()
{
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'; // or readWords[i] (not range checked)
}
EDIT:
For each individual line you would do:
std::string line;
std::vector<std::string> readLines;
while(std::getline(ist, line))
{
readLines.push_back(line);
}
I'm having a problem with this code. After compiling with g++, I run a.out and I get a segmentation fault and no "here" displayed. The code is pretty short:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
bool inWords(vector<string> words, string str);
int main()
{
cout << "here";
vector<string> words;
string str;
istringstream iss;
ifstream file("data.txt", ifstream::in);
// read in words
for(int i = 0; file >> str; /*no i++*/)
{
if(str[str.length() - 1] == '.')
str.erase( str.length()-1);
// if word has a period at the end, erase it
if(!inWords(words, str))
{
// if word is not in vector words, add it
words.push_back(str);
i++;
}
}
// output each word
for (vector<string>::size_type i = 0; i < words.size(); i++)
cout << words[i];
// return to beginning of file
file.clear();
file.seekg(0, ios::beg);
// read in sentences
// to be implemented
file.close();
return 0;
}
bool inWords(vector<string> words, string str)
{
for(int i = 0; !words[i].empty(); i++)
if(words[i] == str) { return true; }
return false;
}
As far as I know, nothing should be a problem. data.txt is definitely in the same directory as the file and I receive no arguments from the command line. Can anyone help?
It won't be before main. Try using a debugger to see where it happens (eg GDB) which are incredibly handy tool. The reason you don't see "here" is because the buffer isn't flushed. Put a << std::endl after it so that it forces output at that point.
A technicality: You can segfault before main but that will happen in a constructor. I see you have no custom objects defined/instantiated in global scope.
The technique for iterating the vector in inWords is wrong and interacts with elements past the end of the vector causing the segmentation fault.
This program immediately accesses words[0] in inWords when the words vector is empty and words[0] (the first element of the vector) does not exist yet because the size of the vector is still zero but the loop does not do anything to avoid this condition.
I think inWords could be better implemented with std::find, perhaps like this:
bool inWords(const vector<string>& words, const string& str)
{
return std::find(words.begin(), words.end(), str) != words.end();
}
Remember to #include <algorithm> to make use of std::find. I also changed the parameters to pass by const reference, so you'll need to change the forward declaration of that function. I also added an endl to the output to make it readable.
Full text of repair:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
bool inWords(const vector<string>& words, const string& str);
int main()
{
vector<string> words;
string str;
istringstream iss;
ifstream file("data.txt", ifstream::in);
// read in words
for(int i = 0; file >> str; /*no i++*/)
{
if(str[str.length() - 1] == '.')
str.erase( str.length()-1);
// if word has a period at the end, erase it
if(!inWords(words, str))
{
// if word is not in vector words, add it
words.push_back(str);
i++;
}
}
// output each word
for (vector<string>::size_type i = 0; i < words.size(); i++)
cout << words[i] << std::endl;
// return to beginning of file
file.clear();
file.seekg(0, ios::beg);
// read in sentences
// to be implemented
file.close();
return 0;
}
bool inWords(const vector<string>& words, const string& str)
{
return std::find(words.begin(), words.end(), str) != words.end();
}
I am attempting to write a program which can read in a text file, and store each word in it as an entry in a string type vector. I am sure that I am doing this very wrong, but it has been so long since I have tried to do this that I have forgotten how it is done. Any help is greatly appreciated. Thanks in advance.
Code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile;
vector<string>::iterator it;
it = input.begin();
readFile.open("input.txt");
for (it; ; it++)
{
char cWord[20];
string word;
word = readFile.get(*cWord, 20, '\n');
if (!readFile.eof())
{
input.push_back(word);
}
else
break;
}
cout << "Vector Size is now %d" << input.size();
return 0;
}
One of the many possible ways is a simple:
std::vector<std::string> words;
std::ifstream file("input.txt");
std::string word;
while (file >> word) {
words.push_back(word);
}
operator >> takes care of only words divided by whitespaces (including new-lines) being read.
And in case you would be reading it by lines, you might also need to explicitly handle empty lines:
std::vector<std::string> lines;
std::ifstream file("input.txt");
std::string line;
while ( std::getline(file, line) ) {
if ( !line.empty() )
lines.push_back(line);
}
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile("input.txt");
copy(istream_iterator<string>(readFile), {}, back_inserter(input));
cout << "Vector Size is now " << input.size();
}
Or, shorter:
int main()
{
ifstream readFile("input.txt");
cout << "Vector Size is now " << vector<string>(istream_iterator<string>(readFile), {}).size();
}
I'm not going to explain, because there's about a zillion explanations on StackOverflow already :)