Write a program in C++ to read the name of the country from one text file, and name of its capital from the second text file. The program must display - turbo-c++

#include <iostream.h>
#include <fstream.h>
#include <conio.h>
void main()
{
if stream fcountry;
if stream fcapital;
char fnm1[20], fnm2[20], str1[20], str2[20];
clrscr();
cout<<"\nEnter country filename-";
cin>>fnm1;
fcountry.open(fnm1);
if(!fcountry)
cout<<"\nCountry file not found";
else
{
cout<<"\nEnter capital filename-";
cin>>fnm2;
fcapital.open(fnm2);
if(!fcapital)
cout<<"\nCountry file not found";
else
{
while(!fcountry.eof())
{
fcountry.getline(str1,20,'\n');
cout<<str1<<"\t";
fcapital.getline(str2,20,'\n');
cout<<str2<<endl;
}
}
}
fcapital.close();
fcountry.close();
getch();
}
Output not showing.

Related

How to use char* with SD library with Arduino?

I am writing a data logger and would like to keep the files limited to a specific number of entries. I am trying to write this bit of code in the setup, so that when the Arduino powers on, it will write to a new file just to keep things simple. However, when I try to open the file I can't, although I am not sure why. Can anyone offer any explanation?
char *fileName; //global name
File logFile; //global file
//everything else is in setup()
char * topPart = "/Data/Data"; //first part of every file
char * lowerPart = ".txt"; // jus the extention
char * itter; //used to hold the char of i later
fileName = "/Data/Data.txt"; //start with the first file possible.
for(int i=0; i<=100;i++) {
if(!SD.exists(fileName)) {
Serial.print("opening file: ");
Serial.print(fileName);
logFile = SD.open(fileName, FILE_WRITE);
if(logFile) {
logFile.println("I made it");
Serial.println("in the file");
}
if(!logFile) {
Serial.println("somthing bad");
}
break;
} else {
itter = (char *)(i+48);
strcpy(fileName,topPart);
strcpy(fileName,itter);
strcpy(fileName,lowerPart);
Serial.println(i);
}
}
Lots of problems.
the construction of itter is wrong.
strcpy doesn't append just cpy.
Here is a code example to build your filename. This a basic C program. Remove the #include and main for Arduino, this allows to test on your computer whether the program is ok.
#include <string.h>
#define TOPPART "/Data/Data"
#define LOWERPART ".txt"
int main(void) {
char buf[64];
snprintf(buf, sizeof(buf), "%s%s", TOPPART, LOWERPART);
for (int i = 0; i < 100; i++) {
/* here your stuff to check if the filename froml buf exists*/
snprintf(buf, sizeof(buf), "%s%d%s", TOPPART, i, LOWERPART);
}
return 0;
}

declaring global struct pointer in c++ for linked list in unix (putty)

I'm trying to create a linked list data structure for a mobile store database. I'm facing problems in declaring a global pointer for struct mobile. In the method view_all(), im not able to get the output of the entered variables.
I'm executing this code as mobile.cpp with the help of putty in unix operating system.
#include <iostream>
#include <iomanip>
using namespace std;
struct mobile
{
char make[15];
char model[10];
float price;
mobile *link;
}*start;
void add_new ()
{
struct mobile *temp, *traverse;
temp = new struct mobile;
traverse = start;
if (start==NULL)
{
temp=start;
}
else
{
while (traverse->link!=NULL)
{
traverse=traverse->link;
}
traverse->link=temp;
}
temp->make="BlackBerry";
temp->model="BB9320";
temp->price=12000;
}
void view_all ()
{
struct mobile *temp;
temp = new struct mobile;
temp=start;
cout <<"Mobile make:"<<temp->make;
cout <<"Mobile price:"<<temp->price;
}
int main ()
{
add_new ();
view_all ();
return 0;
}

Arduino error: does not name a type?

I have written a library, but have problem with error does not name a type. I've tryed everything, searched for couple of hours and no luck. Library is placed in the "libraries" folder of the arduino sketch folder. Please help!!! I am using OSX, but the same problem occurs on Windows also.
This is header file of the library:
#ifndef OpticalSensor_h
#define OpticalSensor_h
#include <Arduino.h>
#include <SD.h>
#include <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>
#include <String.h>
class OpticalSensor
{
public:
OpticalSensor(int analogPort);
void LCDInit(int columns, int rows);
void SerialInit(int bitRate);
void SDInit();
double& ReadFromAnalogPort();
void SDCreateFile(String fileName);
void SDDeleteFile(String fileName);
void SDWriteToFile(String fileName);
void SDStreamToFile(String Text);
void SDOpenFileToStream(String fileName);
private:
int _analogPort;
bool _displayFlag;
Adafruit_RGBLCDShield _lcd;
File _MainRecFile;
double _voltage;
void _LCDClearAll();
void _LCDWriteInTwoRows(String row1, String row2);
void _DelayAndClearLCD(bool returnStatus);
};
#endif
This is .cpp file of the library:
#include <OpticalSensor.h>
Adafruit_RGBLCDShield _lcd;
File _MainRecFile;
double _voltage;
OpticalSensor::OpticalSensor(int analogPort)
{
_analogPort = analogPort;
}
void OpticalSensor::LCDInit(int columns, int rows)
{
_lcd = Adafruit_RGBLCDShield();
_lcd.begin(columns,rows);
}
void OpticalSensor::SerialInit(int bitRate)
{
Serial.begin(bitRate);
_bitRate = bitRate;
while(!Serial) {
//wait until serial is not open
}
}
void OpticalSensor::SDInit()
{
// On the Ethernet Shield, CS is pin 4. It's set as an output by default.
// Note that even if it's not used as the CS pin, the hardware SS pin
// (10 on most Arduino boards, 53 on the Mega) must be left as an output
// or the SD library functions will not work.
pinMode(10, OUTPUT);
//check if SD can be found and initialized. Print also message to
//Serial if initialized and to _lcd if initialized.
if(!SD.begin(4)) {
if(Serial){
Serial.println("Initialization failed!");
}
if(_lcd){
_lcd.print("Init failed!");
}
_DelayAndClearLCD(true);
}
else {
if(Serial) {
Serial.println("Initialization done!");
}
if(_lcd) {
lcd.print("Init done!");
}
_DelayAndClearLCD(false);
}
}
void OpticalSensor::SDCreateFile(String fileName)
{
//check if file allready exists, if not it creates one
//and writes apropriate response to
//lcd and Serial if they are initialized.
if(SD.exists(fileName)) {
if(Serial) {
Serial.println(fileName + " already exists!");
}
if(_lcd) {
_LCDWriteInTwoLines(fileName,"already exists!");
}
_DelayAndClearLCD(false);
}
else
{
if(Serial) {
Serial.println(fileName + "Creating file " + fileName + "...");
}
if(_lcd) {
_LCDWriteInTwoLines("Creating file", fileName);
}
_MainRecFile = SD.open(fileName + ".txt", FILE_WRITE);
_MainRecFile.close();
_DelayAndClearLCD(false);
//check if file was created successffully and print apropriate response
//to lcd and Serial if they are initialized
if(SD.exists(fileName + ".txt")) {
if(Serial) {
Serial.println(fileName + ".txt" + " created successffully!");
}
if(_lcd) {
_LCDWriteInTwoLines(fileName + ".txt", "created!");
}
_DelayAndClearLCD(false);
}
else {
if(Serial) {
Serial.println("error: failed to create file!");
}
if(_lcd) {
_LCDWriteInTwoLines("error: failed to","create file!");
}
_DelayAndClearLCD(false);
}
}
}
//delete file from SD card
void OpticalSensor::SDDeleteFile(String fileName)
{
}
//open file, write data to it, and close file after.
void OpticalSensor::SDWriteToFile(String fileName, String Text)
{
_MainRecFile = SD.open(fileName + ".txt", FILE_WRITE);
_MainRecFile.println(Text);
_MainRecFile.close();
}
//Open file to stream data to it.
void OpticalSensor::SDOpenFileToStream(String fileName)
{
_MainRecFile = SD.open(fileName + ".txt", FILE_WRITE);
}
//Write data to file while file is open.
//Notice that you can stream data only to one file at a time!!!
//For instance, if you have two sensors that you want to
//write data to two different files, you have to use SDWriteToFile
//function!!!
void OpticalSensor::SDStreamToFile(String Text)
{
if(_MainRecFile) {
_MainRecFile.println(Text);
}
}
//close file that you streamed data too.
void OpticalSensor::SDCloseStreaming(String fileName)
{
_MainRecFile.close();
}
//clear entire LCD
void OpticalSensor::_LCDClearAll()
{
_lcd.clear();
_lcd.setCursor(0,0);
}
void OpticalSensor::_LCDWriteInTwoRows(String row1, String row2)
{
//write first String in row1
_lcd.print(row1);
//set cursor to the beginning of row 2
_lcd.setCursor(0,1);
//write second String to row 2
_lcd.print(row2);
}
void OpticalSensor::_DelayAndClearLCD(bool returnStatus)
{
//if Serial or _lcd are initialized, delay for 2 seconds
//and clear LCD
if(Serial || _lcd) {
delay(2000);
if(_lcd)
_LCDClearAll();
}
//terminate
if(bool == true) {
return;
}
}
double& ReadFromAnalogPort()
{
_voltage = analogRead(_analogPort);
return _voltage;
}
And this is the .ino file where library is included:
#include <OpticalSensor.h>
OpticalSensor sensor(0);
void setup() {
sensor.LCDInit(16,2);
sensor.SerialInit(9600);
sensor.SDInit();
sensor.SDCreateFile("test1");
sensor.SDOpenFileToStream("test1");
}
void loop() {
}
this is the error:
In file included from Test_OpticalSensorLib.ino:1:
/Users/gaspersladic/Documents/Arduino/libraries/OpticalSensor/OpticalSensor.h:34:
error: 'Adafruit_RGBLCDShield' does not name a type
/Users/gaspersladic/Documents/Arduino/libraries/OpticalSensor/OpticalSensor.h:35:
error: 'File' does not name a type
The two includes you mention in your comment are essential. 'does not name a type' just means there is no definition for that identifier visible to the compiler. If there are errors in the LCD library you mention, then those need to be addressed - omitting the #include will definitely not fix it!
Two notes from experience which might be helpful:
You need to add all #include's to the main sketch - irrespective of whether they are included via another #include.
If you add files to the library folder, the Arduino IDE must be restarted before those new files will be visible.
I got the does not name a type error when installing the NeoMatrix library.
Solution: the .cpp and .h files need to be in the top folder when you copy it, e.g:
myArduinoFolder/libraries/Adafruit_NeoMatrix/Adafruit_NeoMatrix.cpp
When I used the default Windows unzip program, it nested the contents inside another folder:
myArduinoFolder/libraries/Adafruit_NeoMatrix/Adafruit_NeoMatrix/Adafruit_NeoMatrix.cpp
I moved the files up, so it was:
myArduinoFolder/libraries/Adafruit_NeoMatrix/Adafruit_NeoMatrix.cpp
This fixed the does not name a type problem.
I found the solution to this problem in a "}". I did some changes to my sketch and forgot to check for "}" and I had an extra one. As soon as I deleted it and compiled everything was fine.
Don't know it this is your problem but it was mine.
Void setup() does not name a type
BUT
void setup() is ok.
I found that the sketch I copied for another project was full of 'wrong case' letters. Onc efixed, it ran smoothly.emphasized text
The only thing you have to do is adding this line to
your sketch
#include <SPI.h>
before #include <Adafruit_MAX31855.h>.
More recently, I have found that other factors will also cause this error. I had an AES.h, AES.cpp containing a AES class and it gave this same unhelpful error. Only when I renamed to Encryption.h, Encryption.cpp and Encryption as the class name did it suddenly start working. There were no other code changes.
My code was out of void setup() or void loop() in Arduino.
Usually Header file syntax start with capital letter.I found that code written all in smaller letter
#ifndef DIAG_H
#define DIAG_H
#endif

connecting a signal of widget in a plasmoid

I am new to Qt and am trying to connect the cilicked signal o a push button with a function hile writing a plasmoid. I am trying to use an external function as a public with Plasma::PushButton type object so that I can use it to connect it with the clicked signal? With gtk it was as simple as on_...._clicked do this but isnt there a simple way in qt, where we can do away with the need to use slots?
#include "plasma-tutorial1.h"
#include<string.h>
#include <stdlib.h>
#include <QGraphicsLinearLayout>
#include <QPainter>
#include <QFontMetrics>
#include <QSizeF>
#include <QTextEdit>
#include <plasma/svg.h>
#include <plasma/theme.h>
#include <plasma/widgets/lineedit.h>
#include <plasma/widgets/pushbutton.h>
#include <plasma/widgets/textedit.h>
//PlasmaTutorial1 mainf;
themainfunction(int choice,Plasma::LineEdit *m_lineEdit,
Plasma::TextEdit *m_displaytext)
{
char buffer[100];
const char *inp=(const char *)malloc(sizeof(char)*100);
QString input;
input=m_lineEdit->text();
QByteArray byteArray = input.toUtf8();
inp = byteArray.constData();
char *expression;
expression=(char *)malloc(sizeof(char)*100);
strcpy(expression,"sudo apt-");
switch(choice)
{
case 1:{
strcat(expression,"get install ");
strcat(expression,inp);
break;
};
case 2:{
strcat(expression,"get remove ");
strcat(expression,inp);
break;
};
case 3:{
strcat(expression,"cache search ");
strcat(expression,inp);
break;
};
};
/*
FILE* in;
FILE* ptr=fopen("new.txt","w");
FILE *popen();
if(!(in = popen("cal","r")))
{return;}
while(fgets(buffer, 100, in) != NULL) {
*/
m_displaytext->append("yeah!");
// fprintf(ptr,"%s",buffer);
//}
//pclose(in);
//fclose(ptr);
}
PlasmaTutorial1::PlasmaTutorial1(QObject *parent, const QVariantList &args)
: Plasma::Applet(parent, args),
m_svg(this),
m_icon("document")
{
m_svg.setImagePath("widgets/background");
// this will get us the standard applet background, for free!
setBackgroundHints(DefaultBackground);
resize(200, 200);
}
PlasmaTutorial1::~PlasmaTutorial1()
{
if (hasFailedToLaunch()) {
// Do some cleanup here
} else {
// Save settings
}
}
void PlasmaTutorial1::init()
{
/* // A small demonstration of the setFailedToLaunch function
if (m_icon.isNull()) {
setFailedToLaunch(true, "No world to say hello");
}*/
Counter rt;
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(this);
layout->setOrientation(Qt::Vertical); //so widgets will be stacked up/down
m_lineEdit = new Plasma::LineEdit(this);
m_lineEdit->setText("Enter the package name here");
m_displaytext = new Plasma::TextEdit(this);
m_displaytext->setText("Terminal");
m_installButton = new Plasma::PushButton(this);
m_installButton->setText("Install");
connect(m_installButton, SIGNAL(clicked()),&rt,SLOT(themainfunction(1,m_lineEdit,m_displaytext)));
m_removeButton = new Plasma::PushButton(this);
m_removeButton->setText("Remove");
// m_removeButton->clicked()
connect(m_removeButton, SIGNAL(clicked()),&rt,SLOT(themainfunction(2,m_lineEdit,m_displaytext)));
m_searchButton = new Plasma::PushButton(this);
m_searchButton->setText("Search");
connect(m_searchButton, SIGNAL(clicked()),&rt,SLOT(themainfunction(3,m_lineEdit,m_displaytext)));
layout->addItem(m_lineEdit);
layout->addItem(m_installButton);
layout->addItem(m_removeButton);
layout->addItem(m_searchButton);
layout->addItem(m_displaytext);
m_displaytext->append("yo baby!");
}
/*
void PlasmaTutorial1::paintInterface(QPainter *p,
const QStyleOptionGraphicsItem *option, const QRect &contentsRect)
{
p->setRenderHint(QPainter::SmoothPixmapTransform);
p->setRenderHint(QPainter::Antialiasing);
// Now we draw the applet, starting with our svg
m_svg.resize((int)contentsRect.width(), (int)contentsRect.height());
m_svg.paint(p, (int)contentsRect.left(), (int)contentsRect.top());
// We place the icon and text
p->drawPixmap(7, 0, m_icon.pixmap((int)contentsRect.width(),(int)contentsRect.width()-14));
p->save();
p->setPen(Qt::white);
p->drawText(contentsRect,
Qt::AlignBottom | Qt::AlignHCenter,
"Hello Plasmoid!");
p->restore();
}
*/
// This is the command that links your applet to the .desktop file
K_EXPORT_PLASMA_APPLET(tutorial1, PlasmaTutorial1)
#include "plasma-tutorial1.moc"
say i want to connect themainfunction() upon clicked signal of install button . how do i do it? how can I derive a class in plasma?
i got where was i missing out. We cannot pass objects as arguments in slot functions. Now it is running smooth. thanx for all your replies.

How to use a QFile with std::iostream?

Is it possible to use a QFile like a std::iostream? I'm quite sure there must be a wrapper out there. The question is where?
I have another libs, which requires a std::istream as input parameter, but in my program i only have a QFile at this point.
I came up with my own solution using the following code:
#include <ios>
#include <QIODevice>
class QStdStreamBuf : public std::streambuf
{
public:
QStdStreamBuf(QIODevice *dev) : std::streambuf(), m_dev(dev)
{
// Initialize get pointer. This should be zero so that underflow is called upon first read.
this->setg(0, 0, 0);
}
protected:
virtual std::streamsize xsgetn(std::streambuf::char_type *str, std::streamsize n)
{
return m_dev->read(str, n);
}
virtual std::streamsize xsputn(const std::streambuf::char_type *str, std::streamsize n)
{
return m_dev->write(str, n);
}
virtual std::streambuf::pos_type seekoff(std::streambuf::off_type off, std::ios_base::seekdir dir, std::ios_base::openmode /*__mode*/)
{
switch(dir)
{
case std::ios_base::beg:
break;
case std::ios_base::end:
off = m_dev->size() - off;
break;
case std::ios_base::cur:
off = m_dev->pos() + off;
break;
}
if(m_dev->seek(off))
return m_dev->pos();
else
return std::streambuf::pos_type(std::streambuf::off_type(-1));
}
virtual std::streambuf::pos_type seekpos(std::streambuf::pos_type off, std::ios_base::openmode /*__mode*/)
{
if(m_dev->seek(off))
return m_dev->pos();
else
return std::streambuf::pos_type(std::streambuf::off_type(-1));
}
virtual std::streambuf::int_type underflow()
{
// Read enough bytes to fill the buffer.
std::streamsize len = sgetn(m_inbuf, sizeof(m_inbuf)/sizeof(m_inbuf[0]));
// Since the input buffer content is now valid (or is new)
// the get pointer should be initialized (or reset).
setg(m_inbuf, m_inbuf, m_inbuf + len);
// If nothing was read, then the end is here.
if(len == 0)
return traits_type::eof();
// Return the first character.
return traits_type::not_eof(m_inbuf[0]);
}
private:
static const std::streamsize BUFFER_SIZE = 1024;
std::streambuf::char_type m_inbuf[BUFFER_SIZE];
QIODevice *m_dev;
};
class QStdIStream : public std::istream
{
public:
QStdIStream(QIODevice *dev) : std::istream(m_buf = new QStdStreamBuf(dev)) {}
virtual ~QStdIStream()
{
rdbuf(0);
delete m_buf;
}
private:
QStdStreamBuf * m_buf;
};
I works fine for reading local files. I haven't tested it for writing files. This code is surely not perfect but it works.
I came up with my own solution (which uses the same idea Stephen Chu suggested)
#include <iostream>
#include <fstream>
#include <cstdio>
#include <QtCore>
using namespace std;
void externalLibFunction(istream & input_stream) {
copy(istream_iterator<string>(input_stream),
istream_iterator<string>(),
ostream_iterator<string>(cout, " "));
}
ifstream QFileToifstream(QFile & file) {
Q_ASSERT(file.isReadable());
return ifstream(::_fdopen(file.handle(), "r"));
}
int main(int argc, char ** argv)
{
QFile file("a file");
file.open(QIODevice::WriteOnly);
file.write(QString("some string").toLatin1());
file.close();
file.open(QIODevice::ReadOnly);
std::ifstream ifs(QFileToifstream(file));
externalLibFunction(ifs);
}
Output:
some string
This code uses std::ifstream move constructor (C++x0 feature) specified in 27.9.1.7 basic_ifstream constructors section of Working Draft, Standard for Programming Language C++:
basic_ifstream(basic_ifstream&& rhs);
Effects: Move constructs from the
rvalue rhs. This is accomplished by
move constructing the base class, and
the contained basic_filebuf. Next
basic_istream::set_rdbuf(&sb) is called to install the contained
basic_filebuf.
See How to return an fstream (C++0x) for discussion on this subject.
If the QFile object you get is not open for read already, you can get filename from it and open an ifstream object.
If it's already open, you can get file handle/descriptor with handle() and go from there. There's no portable way of getting a fstream from platform handle. You will have to find a workaround for your platforms.
Here's a good guide for subclassing std::streambuf to provide a non-seekable read-only std::istream: https://stackoverflow.com/a/14086442/316578
Here is a simple class based on that approach which adapts a QFile into an std::streambuf which can then be wrapped in an std::istream.
#include <iostream>
#include <QFile>
constexpr qint64 ERROR = -1;
constexpr qint64 BUFFER_SIZE = 1024;
class QFileInputStreamBuffer final : public std::streambuf {
private:
QFile &m_file;
QByteArray m_buffer;
public:
explicit QFileInputStreamBuffer(QFile &file)
: m_file(file),
m_buffer(BUFFER_SIZE, Qt::Uninitialized) {
}
virtual int underflow() override {
if (atEndOfBuffer()) {
// try to get more data
const qint64 bytesReadIntoBuffer = m_file.read(m_buffer.data(), BUFFER_SIZE);
if (bytesReadIntoBuffer != ERROR) {
setg(m_buffer.data(), m_buffer.data(), m_buffer.data() + bytesReadIntoBuffer);
}
}
if (atEndOfBuffer()) {
// no more data available
return std::char_traits<char>::eof();
}
else {
return std::char_traits<char>::to_int_type(*gptr());
}
}
private:
bool atEndOfBuffer() const {
return gptr() == egptr();
}
};
If you want to be able to more things like seek, write, etc., then you'd need one of the other more complex solutions here which override more streambuf functions.
If you don't care much for performance you can always read everything from the file and dump it into an std::stringstream and then pass that to your library. (or the otherway, buffer everything to a stringstream and then write to a QFile)
Other than that, it doesn't look like the two can inter-operate. At any rate, Qt to STL inter operations are often a cause for obscure bugs and subtle inconsistencies if the version of STL that Qt was compiled with is different in any way from the version of STL you are using. This can happen for instance if you change the version of Visual Studio.

Resources