Appending line from a file into char array [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
char wordList[200];
ifstream wordListFile ("wordlist.txt");
for(std::string line; getline(wordListFile, line); ) {
wordListFile >> wordList;
}
This code currently returns the line at the end of the wordListFile (wordlist.txt),
is there any way to append the lines to wordList?
because when I use the append() function it returns an error.

In the loop
for(std::string line; getline(wordListFile, line); ) {
wordListFile >> wordList;
you are reading one line of input with getline(wordListFile, line);, but not doing anything with that line. Instead, you are reading the first word of the next line with wordListFile >> wordList;. This does not make sense.
If you want to append the line contents to wordList, then you could initialize wordList as an empty string and then use std::strcat:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
int main()
{
char wordList[200] = "";
std::ifstream wordListFile( "wordlist.txt" );
for ( std::string line; std::getline(wordListFile, line); ) {
std::strcat( wordList, line.c_str() );
}
std::cout << wordList << '\n';
}
For the input
This is line 1.
This is line 2.
this program has the following output:
This is line 1.This is line 2.
As you can see, the lines were correctly appended.
However, this code is dangerous, because if the file is too large for the array wordList, then you will have a buffer overflow.
A safer and more efficient approach would be to make wordList of type std::string instead of a C-style string:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string wordList;
std::ifstream wordListFile( "wordlist.txt" );
for ( std::string line; std::getline(wordListFile, line); ) {
wordList += line;
}
std::cout << wordList << '\n';
}
This program has the same output:
This is line 1.This is line 2.

You can only use append on a std::string but your wordList is a char array.
Also a string isn't a list. Probably (but I am guessing) you want code something like this
std::vector<std::string> wordList;
for (std::string word; wordListFile >> word; ) {
wordList.push_back(word);
}
Here wordList is a vector of strings, and push_back adds each word that you read to that vector.
If you actually want to append lines not words to a list then just use getline instead of >>
std::vector<std::string> lineList;
for (std::string line; getline(wordListFile, line); ) {
lineList.push_back(line);
}

because when I use the append() function it returns an error.
std::string::append (2) works well.
std::string wordList;
ifstream wordListFile ("wordlist.txt");
for(std::string line; getline(wordListFile, line); ) {
wordList.append(line);
}

std::string wordList;
std::ifstream wordListFile ;
wordListFile.open("wordlist.txt");
std::getline(wordListFile , wordList);
wordListFile.close();
Try this code. You could get whole string from the file.
I wish this can help you.

Related

extract text between single quotes and between spaces in a string using C++ [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 2 months ago.
Improve this question
I have a text file with lines in this format:
'F1 TEXT' 59 59 2 2 1 1 'X' /
I was able to use getline() to read individual lines. Now, I need to get the strings between single quotes ('F1 TEXT' and 'X'), as well as the numbers delimited by space, into an array or something similar. Any guidance on the appropriate functions or algorithms would be greatly appreciated.
Here is my code so far:
std::ifstream file(file_name);
std::string line;
if (file.is_open()) {
while (std::getline(file, line))
{
// using printf() in all tests for consistency
printf("%s\n", line.c_str());
contents.push_back(line);
}
file.close();
}
After extracting a line, you can put it into a std::istringstream and then extract the individual values from it using operator>>, using the std::quoted I/O manipulator to handle the reading of the quoted strings.
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
struct Data
{
std::string value1;
int value2;
int value3;
int value4;
int value5;
int value6;
int value7;
std::string value8;
char value9;
};
std::istream& operator>>(std::istream &in, Data &data)
{
in >> std::quoted(data.value1, '\x27')
>> data.value2
>> data.value3
>> data.value4
>> data.value5
>> data.value6
>> data.value7
>> std::quoted(data.value8, '\x27')
>> data.value9;
return in;
}
...
std::ifstream file(file_name);
std::string line;
while (std::getline(file, line))
{
std::istringstream iss(line);
Data data;
if (iss >> data) {
// use data as needed...
}
}

Reading all the words in a text file in C++

I have a large .txt file and I want to read all of the words inside it and print them on the screen. The first thing I did was to use std::getline() in this way:
std::vector<std::string> words;
std::string line;
while(std::getline(std::cin,line)){
words.push_back(line);
}
and then I printed out all the words present in the vector words. The .txt file is passed from command line as ./a.out < myTxt.txt.
The problem is that each component of the vector is a whole line, and so I am not reading each word.
The problem, I guess, is the spaces between words: how can I tell the code to ignore them? More specifically, is there any function that I can use in order to read each word from a .txt file?
UPDATE:
I'm trying to avoid all the commas ., but also ? ! (). I used find_first_of(), but my program doesn't work. Also, I don't know how to set what are the characters I don't want to be read, i.e. ., ?, !, and so on
std::vector<std::string> my_vec;
std::string line;
while(std::cin>>line){
std::size_t pos = line.find_first_of("!");
std::string line = line.substr(pos);
my_vec.push_back(line);
}
'>>' operator of type string exactly fills your requirements.
std::vector<std::string> words;
std::string line;
while (std::cin >> line) {
words.push_back(line);
}
If you need remove some noisy characters, e.g. ',','.', you can replace them with space character first.
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::string> words;
std::string line;
while (getline(std::cin, line)) {
std::transform(line.begin(), line.end(), line.begin(),
[](char c) { return std::isalnum(c) ? c : ' '; });
std::stringstream linestream(line);
std::string w;
while (linestream >> w) {
std::cout << w << "\n";
words.push_back(w);
}
}
}
cppreference
The getline function, as it sounds, only returns a whole line. You can split each line on spaces after reading it, or you can read word by word using operator>>:
string word;
while (cin >> word){
cout << word << "\n";
words.push_back(word);
}
Use operator>> instead of std::getline(). The operator will read individual whitespace-separated substrings for you.
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> my_vec;
std::string s;
while (std::cin >> s){
// use s as needed...
}
However, you may still end up receiving strings that have punctuation in them without any surrounding whitespace, ie hello,world, so you will have to manually split those strings as needed, eg:
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
std::vector<std::string> my_vec;
std::string s;
while (std::cin >> s){
std::string::size_type start = 0, pos;
while ((pos = s.find_first_of(".,?!()", start)) != std::string::npos){
my_vec.push_back(s.substr(start, pos-start));
start = s.find_first_not_of(".,?!() \t\f\r\n\v", pos+1);
}
if (start == 0)
my_vec.push_back(s);
else if (start != std::string::npos)
my_vec.push_back(s.substr(start));
}

C++ reading in from file with words seperated by whitespace and new lines [duplicate]

This question already has answers here:
End of File in C++
(3 answers)
Closed 6 years ago.
I'm having an issue reading in from a file that has words seperated by spaces, and with new lines randomly. Here is my code:
vector<string> _vecIgnoreWords;
vector<string> _vecHungerGames;
void readTextFile(char *fileNameHungerGames, vector<string>& _vecHungerGames){
ifstream fileInHungerGames;
string newline;
fileInHungerGames.open(fileNameHungerGames);
if(fileInHungerGames.is_open()){
while(getline(fileInHungerGames, newline)){
stringstream iss(newline);
while(iss){
iss >> newline;
if(!(isCommonWord(newline, _vecIgnoreWords))){
_vecHungerGames.push_back(newline);
cout << newline << endl;
}
}
}
fileInHungerGames.close();
}
The call in main:
string fileName = argv[2];
string fileNameIgnore = argv[3];
char* p = new char[fileNameIgnore.length() + 1];
memcpy(p, fileNameIgnore.c_str(), fileNameIgnore.length()+1);
getStopWords(p, _vecIgnoreWords);
char* hungergamesfile_ = new char[fileName.length() + 1];
memcpy(hungergamesfile_, fileName.c_str(), fileName.length()+1);
readTextFile(hungergamesfile_, _vecHungerGames);
The stop words void:
void getStopWords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords){
ifstream fileIgnore;
string line;
fileIgnore.open(ignoreWordFileName);
if(fileIgnore.is_open()){
while(getline(fileIgnore, line)){
_vecIgnoreWords.push_back(line);
}
}
fileIgnore.close();
return;
}
My problem currently is that My output for this code ends up something like:
bread
is
is
slipping
away
take
I'm not sure why i'm getting repeats (is is) and the empty lines when I am using a string stream?
my output should look like:
bread
is
slipping
away
from
me
Also slightly less important but my while loop is looping once too many which is why I have the if(_vecHungerGames.size() == 7682) is there a way to fix this loop from looping once too many?
File example:
bread is
slipping away from me
i take his hand holding on tightly preparing for the
Try something more like this:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
std::vector<std::string> _vecIgnoreWords;
std::vector<std::string> _vecHungerGames;
void getStopWords(const char *filename, std::vector<std::string>& output)
{
std::ifstream file(fileName);
std::string s;
while (std::getline(file, s))
output.push_back(s);
}
void readTextFile(const char *filename, std::vector<std::string>& output)
{
std::ifstream file(fileName);
std::string s;
while (file >> s)
{
if (!isCommonWord(s, _vecIgnoreWords))
{
output.push_back(s);
std::cout << s << std::endl;
}
}
}
int main()
{
getStopWords(argv[3], _vecIgnoreWords);
readTextFile(argv[2], _vecHungerGames);
// use _vecHungerGames as needed...
return 0;
}

No matching function for call to 'get line' while exploding

No matching function for call to 'getline' when using this code:
ifstream myfile;
string line;
string line2;
myfile.open("example.txt");
while (! myfile.eof() )
{
getline (myfile, line);
getline (line, line2, '|');
cout<<line2;
}
In the example.txt i have info like this:
1|Name1|21|170
2|Name2|34|168
etc...
I really want to get the line till the | char...
I try few explode functions but they are only in string type but i need:
1st to be int
2nd to be char
3rd and 4th to be float.
It's really complicated that i want to do, and i can't explain it well. I hope someone will understand me.
getline receives as first argument an instance of the template basic_istream. string doesn't meet that requirement.
You could use stringstream:
#include <sstream>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string line;
string line2;
ifstream myfile("test/test.txt");
while (getline(myfile, line))
{
stringstream sline(line);
while (getline(sline, line2, '|'))
cout << line2 << endl;
}
return 0;
}

is it possible to read from a specific character in a line from a file in c++?

Hey all so I have to get values from a text file, but the values don't stand alone they are all written as this:
Population size: 30
Is there any way in c++ that I can read from after the ':'?
I've tried using the >> operator like:
string pop;
inFile >> pop;
but off course the whitespace terminates the statement before it gets to the number and for some reason using
inFile.getline(pop, 20);
gives me loads of errors because it does not want to write directly to string for some reason..
I don't really want to use a char array because then it won't be as easy to test for the number and extract that alone from the string.
So is there anyway I can use the getline function with a string?
And is it possible to read from after the ':' character?
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
string fname;
cin >> fname;
ifstream inFile;
inFile.open(fname.c_str());
string pop1;
getline(inFile,pop1);
cout << pop1;
return 0;
}
ok so here is my code with the new getline, but it still outputs nothing. it does correctly open the text file and it works with a char array
You are probably best to read the whole line then manipulate the string :-
std::string line;
std::getline(inFile, line);
line = line.substr(19); // Get character 20 onwards...
You are probably better too looking for the colon :-
size_t pos = line.find(":");
if (pos != string::npos)
{
line = line.substr(pos + 1);
}
Or something similar
Once you've done that you might want to feed it back into a stringstream so you can read ints and stuff?
int population;
std::istringstream ss(line);
ss >> population;
Obviously this all depends on what you want to do with the data
Assuming your data is in the form
<Key>:<Value>
One per line. Then I would do this:
std::string line;
while(std::getline(inFile, line))
{
std::stringstream linestream(line);
std::string key;
int value;
if (std::getline(linestream, key, ':') >> value)
{
// Got a key/value pair
}
}