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.
solved Appending line from a file into char array [closed]