I've written the following in windows on Qt IDE and when I run it, it works well, however when I tried to run it on centOS with, I want to run code using threads, in which I'm just tring to load a CSV file and write the results within it in centos envirements
g++ -std=gnu++11 main.cpp -o main
I get the errors
does any solution to this issue ?
code
#include <iostream> // for standard I/O
#include <string> // for strings
#include <iomanip> // for controlling float print precision
#include <sstream> // string to number conversion
#include <ctime>
#include <future>
#include <fstream>
#include <string>
/*
*
* error This file requires compiler and library support for the ISO C++ 2011 standard.
* This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
*
*/
using namespace std;
stringstream processing (int x,int id) {
std::cout << "Calculating. Please, wait...\n";
stringstream cvsStream;
for(int i = 0 ; i < x ; ++i){
cvsStream <<i<<","<<i<<","<<i<<","<<i<<"\n";
cout <<id<< " / "<<i<< endl;
}
return cvsStream;
}
int main(int argc, char *argv[])
{
string filename = "OutputFile.csv";
ofstream myfile;
stringstream cvsStream;
myfile.open(filename);
// If file does not exist, Create new file
if (!myfile )
{
cout << "Cannot open file, file does not exist. Creating new file..";
myfile.open(filename, fstream::in | fstream::out | fstream::trunc);
myfile <<"\n";
}
// open csv file
cvsStream <<" AD_ID "<<","<<"Starts at "<<","<<"At_Frame"<<","<<"Ends at "<<"\n";
myfile << cvsStream.str();
cvsStream.str("");
auto outputRslt1 = std::async (processing,1000,1);
auto outputRslt2 = std::async (processing,1000,2);
auto outputRslt3 = std::async (processing,1000,3);
stringstream rsltThread1 = outputRslt1.get();
stringstream rsltThread2 = outputRslt2.get();
stringstream rsltThread3 = outputRslt3.get();
// close csv file
myfile << rsltThread1.str();
myfile << rsltThread2.str();
myfile << rsltThread3.str();
myfile.close();
return 0;
}
errors
main.cpp: In function ‘std::stringstream processing(int, int)’:
main.cpp:22:8: error: use of deleted function ‘std::basic_stringstream<char>::basic_stringstream(const std::basic_stringstream<char>&)’
return cvsStream;
In file included from main.cpp:4:0:
/usr/include/c++/4.8.2/sstream:502:11: note: ‘std::basic_stringstream<char>::basic_stringstream(const std::basic_stringstream<char>&)’ is implicitly deleted because the default definition would be ill-formed:
class basic_stringstream : public basic_iostream<_CharT, _Traits>
In fact, Streams are not copyable, Unfortunately GCC 4.8 had not yet added the move constructor that was necessary for this to work. C++11 made them moveable and this is what makes it possible to return a local stringstream object from a function.
you can use function return the result as a string and consider as a solution or upgrade to a later version of GCC.
#include <iostream> // for standard I/O
#include <string> // for strings
#include <iomanip> // for controlling float print precision
#include <sstream> // string to number conversion
#include <ctime>
#include <future>
#include <fstream>
#include <string>
/*
*
* error This file requires compiler and library support for the ISO C++ 2011 standard.
* This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
*
*/
using namespace std;
string processing (int x,int id) {
std::cout << "Calculating. Please, wait...\n";
stringstream cvsStream;
for(int i = 0 ; i < x ; ++i){
cvsStream <<i<<","<<i<<","<<i<<","<<i<<"\n";
cout <<id<< " / "<<i<< endl;
}
return cvsStream.str();
}
int main(int argc, char *argv[])
{
string filename = "OutputFile.csv";
ofstream myfile;
stringstream cvsStream;
myfile.open(filename);
// If file does not exist, Create new file
if (!myfile )
{
cout << "Cannot open file, file does not exist. Creating new file..";
myfile.open(filename, fstream::in | fstream::out | fstream::trunc);
myfile <<"\n";
}
// open csv file
cvsStream <<" AD_ID "<<","<<"Starts at "<<","<<"At_Frame"<<","<<"Ends at "<<"\n";
myfile << cvsStream.str();
cvsStream.str("");
auto outputRsl1 = std::async (processing,1000,1);
auto outputRsl2 = std::async (processing,1000,2);
auto outputRsl3 = std::async (processing,1000,3);
string rslThread1 = outputRsl1.get();
string rslThread2 = outputRsl2.get();
string rslThread3 = outputRsl3.get();
// close csv file
myfile << rslThread1;
myfile << rslThread2;
myfile << rslThread3;
myfile.close();
return 0;
}
Related
Hey guys I'm new to this,
I managed to make c++ open a random .jpg file from a folder using srand, the files are named sequentially 1-25.
Now I want to print out which file has been chosen by the randomizer every time I run the programm and log it into a .txt file.
The log in the .txt file should look like this:
4
8
5
..and so on, so that it adds the result of the randomizer to a new line each time it gets executed.
This is the code I have so far:
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <fstream>
using namespace std;
int main()
{
srand((unsigned)time(0));
ostringstream oss;
oss << "\"C:\\Users\\etc..";
oss << rand() % 25 + 1;
oss << ".jpg\"";
system(oss.str().c_str());
system("pause");
return 0;
}
See below a complete example how you can achieve what you described.
The function LogToFile uses std::ofstream to open a file in append mode, and write to it.
You can change it if you'd like a different format (e.g. separate by commas instead of newline).
In order to call it with the number I added a variable n to hold the number (rather than streaming it directly into the std::ostringstream).
A side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
The code:
#include <string>
#include <ctime>
#include <fstream>
#include <sstream>
#include <assert.h>
bool LogToFile(std::string const & filename, int n)
{
std::ofstream file;
file.open(filename, std::ios_base::app); // open in append mode
if (!file.is_open())
{
return false;
}
file << n << std::endl;
file.close();
return true;
}
int main()
{
// change according to your needs:
const std::string LOG_FILENAME = "log.txt";
const std::string IMAGE_FOLDER = "C:\\tmp";
srand((unsigned)time(0));
int n = rand() % 25 + 1;
// Add the number to the log file:
bool bRes = LogToFile(LOG_FILENAME, n);
assert(bRes);
std::ostringstream oss;
oss << "\"" << IMAGE_FOLDER << "\\" << n << ".jpg" << "\"";
system(oss.str().c_str());
system("pause");
return 0;
}
i'm trying to write a script in c++ which read a CSV file so i can treat it later .i ve used fstram but the file always fail to open**
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
string filename = "hello.txt"; // could come from command line.
ifstream fin(filename.c_str());
if (!fin.is_open())
{
cout << "Could not open file: " << filename << endl;
return 1;
}
cout<<"khalil"<<endl;
string scores[32];
string names[32];
int iter = 0;
while (iter <= 5)
{
fin >> names[iter] >> scores[iter];
cout << iter <<"\n";
cout<<names[iter]<< "\n";
cout<<scores[iter]<<"\n";
iter++;
}
fin.close();
}
Try using a fully qualified path name, e.g.:
string filename = "C:\\Documents\\hello.txt";It appears your program isn't opening the file because it can't find it.
You can use QFile class to do this operation.
#include <QFile>
#include <QStringList>
#include <QDebug>
int main()
{
QFile file("C\\hello.txt");
if (!file.open(QIODevice::ReadOnly)) {
qDebug()<<file.errorString();
return 0;
}
QStringList firstList, secondList;
while (!file.atEnd()) {
QByteArray line = file.readLine();
firstList.append(line.split(',')[0]);
secondList.append(line.split(',')[1]);
}
qDebug()<<firstList;
qDebug()<<secondList;
}
I am trying to make my first class with a constructor and it seems to be acting strangely.
My class is derived from filebuf and for some reason, I am unable to open it in the constructor.
I tried to add a cout statement for debugging, but the << operator is not recognized.
#include <iostream>
#include "bin.h"
int main()
{
bin myBin("e:\Temp\test.txt");
system("PAUSE");
return 0;
}
bin.h
#pragma once
#include <fstream>
#include <cstdlib>
#include <cstring>
class bin : private std::filebuf {
int buffSize = 1000;
char* buffer;
unsigned int length;
short int buffCounter;
public:
bin(std::string fileName)
{
open(fileName.c_str(), std::ios::in | std::ios::out | std::ios::trunc);
if (!is_open())
std::cout << "ERROR: failed to open file " << fileName << std::endl;
//set all IO operations to be unbufferred, buffering will be managed manually
setbuf(0, 0);
//create buffer
buffer = new char[buffSize];
};
virtual ~bin()
{
delete buffer;
};
};
bin myBin("e:\Temp\test.txt");
You have to correct above line as follows:
bin myBin("e:\\Temp\\test.txt");
DEMO: http://cpp.sh/7b4k
It looks like you need:
#include <iostream>
To use std::string you need:
#include <string>
The iostream include may have forward-declared std::string but without the full definition you don't get operator<< (or c_str()).
Some other answerers may be unable to reproduce your problem because different standard libraries might have their iostream fully do #include <string> (this is permitted but not required).
std::cout << "ERROR: failed to open file " << fileName << std::endl;
Should be
std::cout << "ERROR: failed to open file " << fileName.c_str() << std::endl;
std::cout doesn't always accept std::string but does accept const char *
This is what I tried:
#include <iostream>
#include <string>
int main(int argc, char const *argv[]) {
using namespace std;
for (string cin_line; getline(cin, cin_line);) {
cout << cin_line << endl;
}
FILE* pipe = popen("app.exe", "r");
for (string result_line; getline(pipe, result_line);) {
cout << result_line << endl;
}
pclose(pipe);
return 0;
}
It doesn't compile, the result is:
no matching function for call to 'getline(FILE*&, std::__cxx11::string&)'
Second example I've found here: https://stackoverflow.com/a/10702464/393087
But it seems mingw doesn't have pstream included: fatal error: pstream.h: No such file or directory - edit: ok I know, I missed that this is not a GCC library, it is named like it was but this is separate download: http://pstreams.sourceforge.net/
I know how to do it using buffer and get whole output on single line (like here: https://stackoverflow.com/a/478960/393087 ) then explode the line by \n and get my array, but the point here is that I must provide the output as soon as the input comes in.
Also I tried example from here: https://stackoverflow.com/a/313382/393087 - I've added main function to that:
#include <cstdio>
#include <iostream>
#include <string>
int main(int argc, char const *argv[]) {
using namespace std;
FILE * fp ;
if((fp= popen("/bin/df","r")) == NULL) {
// error processing and exit
}
ifstream ins(fileno(fp)); // ifstream ctor using a file descriptor
string s;
while (! ins.eof()){
getline(ins,s);
// do something
}
return 0;
}
This also doesn't compile:
error: variable 'std::ifstream ins' has initializer but incomplete type
ifstream ins(fileno(fp)); // ifstream ctor using a file descriptor
You can't do this:
FILE* pipe = popen("app.exe", "r");
for (string result_line; getline(pipe, result_line);) {
cout << result_line << endl;
}
pclose(pipe);
You need to do this:
#include <boost/noncopyable.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
FILE* pipe = popen("app.exe", "r");
boost::iostreams::file_descriptor_source
source(fileno(pipe), boost::iostreams::never_close_handle);
boost::iostreams::stream<boost::iostreams::file_descriptor_source>
stream(source, 0x1000, 0x1000);
string result_line;
while (getline(stream, result_line)) {
cout << result_line << endl;
}
:)
Basically I need to open and read a list of files I get from another command.
For each line of output of popen
open a file usen ifstream.open
it compiles and if I put the file name directly it works fine, but it doesn't do anything when using popen output. I've seen questions like this but none of this particular way of giving filenames.
here's the code:
#include <iostream>
#include <sqlite3.h>
#include <stdio.h>
#include <fstream>
using namespace std;
int main () {
ifstream singlefile;
FILE *filelist;
char filename[512];
string progline;
if(!(filelist = popen("find `pwd` -name \"*.js\"", "r"))){
return 1;
}
while( fgets(filename, sizeof(filename), filelist)!=NULL)
{
cout << filename;
singlefile.open(filename, ifstream::in);
while ( singlefile.good() )
{
getline (singlefile,progline);
cout << progline << endl;
}
singlefile.close();
}
pclose(filelist);
return 0;
}
next step would be not open each file inside the loop but to store the file list and then open each file.
Thanks
fgets keeps the trailing newline, resulting in a filename of a non-existing file. Also the stream state is only updated after reading. If I replace the while body with the following code, it works for me:
cout << filename;
size_t len = strlen(filename);
// chop off trailing newline
if (len > 1 && filename[len - 1] == '\n') filename[len - 1] = 0;
singlefile.open(filename, ifstream::in);
while ( getline(singlefile, progline) )
{
cout << progline << endl;
}
singlefile.close();
If you actually want to iterate through a list of files, I'd use Boost.Filesystem, which has a nice C++ interface, works for all filenames (even for those with newlines), and is platform-independent.
If this actually is only an example and your actual command is not find, there is still some room for simplification. Here is a suggestion that uses Boost.Iostreams to get rid of most of the C function calls (it would be great to have a device source reading from a process's standard output, but Boost.Iostreams lacks that):
#include <cstdio>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <stdio.h>
#include <boost/noncopyable.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
using namespace std;
namespace io = boost::iostreams;
class Popen: private boost::noncopyable {
public:
explicit Popen(const char* command):
m_stream(popen(command, "r")) {
if (!m_stream) throw runtime_error("popen failed");
}
~Popen() {
pclose(m_stream);
}
FILE* stream() const {
return m_stream;
}
private:
FILE* m_stream;
};
int main() {
Popen pipe_wrapper("find `pwd` -name \"*.cpp\"");
io::file_descriptor_source pipe_device(fileno(pipe_wrapper.stream()), io::never_close_handle);
io::stream<io::file_descriptor_source> pipe_stream(pipe_device, 0x1000, 0x1000);
string filename;
while (getline(pipe_stream, filename)) {
cout << filename << endl;
ifstream file_stream(filename.c_str(), ifstream::in);
string progline;
while (getline(file_stream, progline)) {
cout << progline << endl;
}
}
}