I was trying to open file and read it using C++. Here's the code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void open_file(string filename)
{
string data;
ifstream file;
file.open(filename);
file >> data;
cout << data;
}
int main()
{
open_file("file.txt");
}
But the output ends when character in file is space.
File:
This message will be printed
Output:
This
Could somebody help me?
Yes. That is the standard behaviour of the extractor.
You should use std::getline to read a complete line. This will read until the end of a line (denoted by '\n').
So:
std::getline(file, data);
Please see here for more information.
Use std::getline()
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void open_file(string filename)
{
string data;
ifstream file;
file.open(filename);
getline(file,data); //This will read until the end of a line
cout << data;
}
int main()
{
open_file("file.txt");
}
Don't use using namespace std , refer to this for more info Why is using namespace std bad?
For more information i recommend getting used to This site
Related
I'm replicating the TextQuery example in C++ Primer 5th edition. The code compiles, but it keeps throwing "read access violation" from Vector header when a push_back operation is executed. Here's my code (* is the line with bug):
//main.cpp
#include "stdafx.h"
using namespace std;
int main()
{
ifstream ifile;
ifile.open("D:/OneDrive/Learning/C++/ConsoleApplication1/ConsoleApplication1/testfile.txt");
runQueries(ifile); //*
// ...
}
//stdafx.h
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <vector>
#include <string>
#include <memory>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <iterator>
#include <sstream>
#include <map>
#include <set>
#include "TextQuery.h"
//TextQuery.h
void runQueries(ifstream &infile)
{
TextQuery tq(infile); //*
// ...
}
class TextQuery {
public:
using line_no = std::vector<std::string>::size_type;
TextQuery(std::ifstream&); //*
// ...
private:
std::shared_ptr<std::vector<std::string>> file;
std::map < std::string, std::shared_ptr<std::set<line_no>>> wm;
};
TextQuery::TextQuery(std::ifstream &is)
{
string text;
while (getline(is, text)) {
file->push_back(text); //*
//...
}
}
The next execution will raise an exception in vector header:
bool _Has_unused_capacity() const _NOEXCEPT
{ // micro-optimization for capacity() != size()
return (this->_Myend() != this->_Mylast());
}
Here's the error message:
Exception thrown: read access violation.
std::_Vector_alloc<std::_Vec_base_types<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > > >::_Myend(...) returned 0xC.
Here's the text file I used for testing:
//text file
text is good
text is good
text is good
text is good
text is good
text is good
text is good
text is good
text is good
As pointed out by #molbdnilo: I forgot to allocate "file".
After changing the constructor to the following, the problem is solve:
TextQuery::TextQuery(std::ifstream &is):file(new vector<string>)
{
string text;
while (getline(is, text)) {
file->push_back(text); //*
//...
}
}
Error: multiple definition of `GameKey::getGameKeywords()'
GameKey.cpp and .h cause error, while ExitKey.cpp and .h are essentially the exact same class and header but do not produce an error.
(I know the whole thing about using namespace std)
//Function Declarations
#ifndef GAMEKEY_H
#define GAMEKEY_H
// C++ libraries
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
class GameKey
{
private:
string keyString;
string lineData;
public:
// Default constructor
GameKey();
// Deconstructor
~GameKey();
// Get keywords
string getGameKeywords();
};
#endif
GameKey.cpp
//Function Definitions
#include "GameKey.h"
// Constructor
GameKey::GameKey()
{
}
// Deconstructor
GameKey::~GameKey()
{
}
// Get keywords
string GameKey::getGameKeywords()
{
ifstream infile;
infile.open("GameKey.txt");
while (getline(infile, lineData))
{
keyString.append(lineData);
keyString.append("\n");
}
infile.close();
return keyString;
}
ExitKey.h
//Function Declarations
#ifndef EXITKEY_H
#define EXITKEY_H
// C++ libraries
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
class ExitKey
{
private:
string keyString;
string lineData;
public:
// Default constructor
ExitKey();
// Deconstructor
~ExitKey();
// Get keywords
string getExitKeywords();
};
#endif
ExitKey.cpp
//Function Definitions
#include "ExitKey.h"
// Constructor
ExitKey::ExitKey()
{
}
// Deconstructor
ExitKey::~ExitKey()
{
}
// Get keywords
string ExitKey::getExitKeywords()
{
ifstream infile;
infile.open("ExitKey.txt");
while (getline(infile, lineData))
{
keyString.append(lineData);
keyString.append("\n");
}
infile.close();
return keyString;
}
Thanks for any help!
I think you probably include GameKey.cpp instead of GameKey.h elsewhere
I am not certain as the command used for compilation is not posted.
One possibility is repeating the file names in your compilation command could also lead to this error.
for example :-
g++ ExitKey.cpp GameKey.cpp GameKey.cpp main.cpp -o main
Hi I just started to learn C++ this week and I require some assistance.
Basically what I am trying to do is read from a .txt file and "convert" it into a vector string and then display it.
my error is at this line: text.readFile("scenario.txt"), it says: "request for member 'readFile' in 'text', which is of non-class type 'Conversion()'"
what does that mean?
and also my method getLines() could not be resolved.
main.cpp
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include "Conversion.h"
using namespace std;
int main()
{
vector<string> lines;
Conversion text();
if(text.readFile("scenario.txt") == true)
lines = text.getLines();
for(int i = 0; i < lines.size(); ++i)
cout << lines[i] << endl;
return 0;
}
Conversion.cpp
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include "Conversion.h"
using namespace std;
vector<string> lines;
Conversion::Conversion(std::vector<std::string> lines) {
lines.clear();
}
Conversion::Conversion() {
}
Conversion::~Conversion() {
}
bool Conversion::readFile(string filename) {
ifstream file;
string line;
file.open(filename.c_str());
if(!file.is_open())
return false;
while(getline(file, line))
lines.push_back(line);
return true;
}
vector<string> Conversion::getLines(){
return lines;
}
Conversion.h
#ifndef CONVERSION_H_
#define CONVERSION_H_
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
class Conversion {
public:
Conversion();
Conversion(std::vector <std::string>);
~Conversion();
std::vector<std::string> getLines();
bool readFile(std::string);
private:
std::vector<std::string> lines;
std::string line;
std::ifstream file;
};
#endif
Once again, Conversion text(); is a function declaration, not a class instantiation. To call the default constructor, change it to Conversion text;
You probably wanted to copy the passed lines in your constructor:
Conversion::Conversion(std::vector<std::string> const& lines) : lines(lines) { }
Your code should work now, but there can be done some improvements. To avoid copy, getLines should return by reference-to-const:
std::vector<std::string> const& getLines();
// you don't have to create lines in main, you can print like this:
for(auto const& x : text.getLines())
cout << x << endl;
and I'd use it even here:
bool readFile(std::string const&);
I hope this is the last thing - std::ifstream constructor and open function also take std::string:
file.open(filename);
You need to remove the parentheses when instantiating the Conversion object:
Conversion text;
See this question for detailed answers: Is no parentheses on a constructor with no arguments a language standard?
I have a simple logger class which I tried to turn into accepting and outputting wstrings instead strings.
header:
#include <fstream>
using namespace std;
class CLog
{
public:
CLog(wstring filename);
~CLog();
void WriteString(string uString);
private:
fstream m_stream;
};
cpp:
#include "stdafx.h";
#include "log.h";
CLog::CLog(wstring uPath)
{
m_stream.open(uPath);
}
void CLog::WriteString(string uString)
{
m_stream << uString.c_str() << endl;
}
CLog::~CLog()
{
m_stream.close();
}
Can anybody suggest what I should use instead of fstream?
I tried using wstringstream, but it did not even have .open to output it to file, so I thought that is the wrong approach.
I would like to keep the behaviour that it immediately writes to a file.
I use "wofstream" instead of "fstream" now, and it works perfectly.
i can't get rid of these errors... i have semicolons everywhere i checked...
the code is simple:
the error takes me to the definition "string name" in article.h...
main.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
#include "article.h"
int main()
{
string si;
char article[128];
vector<Article> articles;
ifstream file;
file.open("input.txt",ifstream::in);
while(!file.eof())
{
file.getline(article,128);
articles.push_back(Article(article));
}
file.close();
while(1);
return(1);
}
article.h:
#ifndef Article_H
#define Article_H
class Article
{
public:
int year;
string name;
Article(char *i_name);
};
#endif
You should add:
#include <string>
to your "article.h" header file and declare name like this:
std::string name;
It seems the string type is not defined in the artivle.h file. Try to include iostream and add using namespace std (or write std::string instead of using namespace)
You should use the std:: namespace prefix in the header, like
std::string name;