How to copy a line with fstream including white spaces? - copy

So if the file i was reading from contained:
2:Hello World
i would like for num to equal the number at the start of each line
and text equal the remaining string of the line
My question is how would i be able make it so my ifstream takes the entire line, including the spaces between words? instead of it taking only "Hello"
#include <fstream>
using namespace std;
int main(int argc, char *argv[]) {
ifstream fin;
fin.open(file);
string s = "";
fin >> s;
loadPacket(s);
}
void loadPacket(string s) {
static const size_t npos = -1;
num = pString.substr(0,1);
text = pString.substr(4, npos);
}

Related

Accounting for space between character search

Im having issues with my code. Its been a few years since I last wrote a even a basic program. My current issue is my program is supposed to count the number of characters entered by the user and return the count of a single char also entered by the user. Where am I going wrong at? I know it has to do with the space between words. Probably a noob mistake. Thanks in advance.
#include <iostream>
#include <string>
#include<stdio.h>
#include<ctype.h>
using namespace std;
int numTimesAppear(char *mystring, char ch)//numTimes Appear function
{
int i;
int count=0;
for (i = 0; i < 100; i++)
{
if (mystring[i] == ch)
count++;
}
return count;
}
int main()
{
char str[100];
char ch;
int nooftimes;
cout << ("Enter a string of characters:") << endl;
cin >> str;
cout << ("Enter a character to count:") << endl;
cin >> ch;
cout << numTimesAppear(str, ch);
return 0;
}

Lex Program to check for comment lines

Could anyone please help me in writing a LEX program to check and count comment lines in a C program. I have searched for it everywhere and failed to get the complete code.
comment lines are of the form
%%
{START} {whatever symbols,alphanumerics and letters} {END}
%%
START symbol can be // or /* in C.
END symbol is */
If it is "//" any other symbol can follow it in the LINE including a second occurances of // (which is ignored).
IF it is " /* " it will find the next immediate match for " */ " and all the rest of the patterns that appear in between is matched(This matching may include blank spaces,tabs ,"//" and " /* " in it)
Here is a sample code to do it
`
%{
#include<stdio.h>
int c=0;
%}
START "/*"
END "*/"
SIMPLE [^*]
SPACE [ \t\n]
COMPLEX "*"[^/]
%s newstate
%%
"//"(.*[ \t]*.*)*[\n]+ {c++; fprintf(yyout," ");}
{START} {yymore();BEGIN newstate;}
<newstate>{SIMPLE} {yymore();BEGIN newstate;}
<newstate>{COMPLEX} {yymore();BEGIN newstate;}
<newstate>{SPACE} {yymore();BEGIN newstate;}
<newstate>{END} {c++;fprintf(yyout," ");BEGIN 0;}
%%
main()
{//program to remove comment lines
yyin=fopen("file4","r");
yyout=fopen("fileout4","w");system("cat file4");
yylex();system("cat fileout4");
printf("no.of comments=%d",c);
fclose(yyin);
fclose(yyout);
}
`
The input file "file4" is below
/* #include <stdlib.h>
{}.#All nonsense symbols */
//another comment
int main{}
{/**/
printf("hello");
/* comment inside// comment is ignored */
//how about//this?
/* now we /* try this */ */
printf("COOL!!");
return (0);
}
It gives the following output which is stored in "fileout4" `
int main{}
{
printf("hello");
*/
printf("COOL!!");
return (0);
}
`
The number of comment lines in the above program is 6.
You can maintain a boolean variable which keeps track of whether the line you're parsing is inside a multi-line comment or not.
%{
#include <stdio.h>
#include <stdbool.h>
int comment_lines = 0;
bool in_comment = false;
%}
%%
"/*".*\n { in_comment = true; ++comment_lines; }
.*"*/"\n { in_comment = false; ++comment_lines; }
"//".*\n { ++comment_lines; }
.*\n {
if (in_comment) {
++comment_lines;
} else {
fprintf(yyout, yytext);
}
}
%%
int yywrap() {
return 1;
}
int main(void) {
printf("Enter input file: ");
char filename[64];
scanf("%s", filename);
yyin = fopen(filename, "r");
printf("Enter output file: ");
scanf("%s", filename);
yyout = fopen(filename, "w");
yylex();
printf("Number of comments: %d\n", comment_lines);
}
In the above code, in_comment is used to indicate the state of the line being analyzed. If it is in a comment, the comment_lines value is incremented, otherwise the text is written to an output file given by yyout.
input file
#include <stdio.h>
/*
*
* This is a multi-line comment
*
*/
void dummy();
// main function is the entry point.
int main(void) {
/*
* Here we print a message on user's
* console.
*/
printf("Hello world\n");
// That is it.
}
output file generated after lexical analysis
#include <stdio.h>
void dummy();
int main(void) {
printf("Hello world\n");
}
Number of comments: 11
%{
#undef yywrap
#define yywrap() 1
int single=0, multiline =0;
%}
%%
"//".*"\n" {printf("%s\n", yytext); single++;}
"/*".*[\n]*.*"*/" {printf("%s\n", yytext); multiline++;}
.;
%%
int main()
{
yyin = fopen("yourfile","r");
yylex(); //calling the rules section
printf(" Single line comments = %d, multiline comments = %d", single, multiline);
fclose(yyin);
}

trying to link two cpp files with a header

I'm trying to call a function from a cpp file (with a list of functions) in another cpp file, I'm using a header file to set the function prototype in both cpp files, my problem is that I'm getting this LNK2019 error. I don't know what i'm doing wrong. I've been going back and forth between a few variations, the current one seems to be the most correct based on what i've read. I've been working on this for hours, reading a bunch of threads, but nothing seems to explain this problem, i'm using microsoft visual studio 2012
this is the header file, Rectangle.h
#pragma once
class Rectangle
{
private:
int width, height;
double gravWidth, gravHeight;
public:
Rectangle();
double getAreaBig();
double getAreaSmall();
int getPerimeter();
void getLength(int b);
void getWidth(int a);
int setLength();
int setWidth();
~Rectangle();
};
this is the cpp file containing the functions, Rectangle.cpp
#include <iostream>
#include "Rectangle.h"
using namespace std;
Rectangle::Rectangle()
{
width = 1;
height = 1;
gravWidth = .5;
gravHeight = .5;
}
double Rectangle::getAreaBig ()
{
return double ((width * height) - (gravWidth * gravHeight));
}
double Rectangle::getAreaSmall()
{
return ((gravWidth) * ( gravHeight));
}
int Rectangle::getPerimeter()
{
return (2 * (width + height));
}
void Rectangle::getLength(int b)
{
height = b;
gravWidth = (1/2 * width);
}
void Rectangle::getWidth(int a)
{
width = a;
gravHeight = (1/2 * height);
}
int Rectangle::setLength()
{
return height;
}
int Rectangle::setWidth()
{
return width;
}
what follows is the app.cpp file, this is where i'm getting the errors, italics are where the errors seem to be pointing too
#include <iostream>
#include "Rectangle.h"
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <cmath>
#include <string>
#include <sstream>
#include <cstddef>
using namespace std;
int main ()
{
int const WIDTH = 10;
setprecision(2);
int length = 0;
int width = 0;
cin >> width;
cin >> length;
Rectangle garden;
Rectangle gravel;
garden.getLength(length);
garden.getWidth(width);
cout << "Length of lawn: " << garden.setLength() << "Width of lawn: " << garden.setWidth();
cout << "Cost of grass: " << garden.getAreaBig();
cout << "Length of gravel: ";
cout << "Width of gravel: ";
cout << "Cost of gavel: ";
system ("pause");
}
The first thing that I see is that you are not instantiating the rectangles.
What about defining
~Rectangle();
somewhere? If your destructor is not going to do anything, you can just provide an empty body in the header file.
~Rectangle() {};
(And just in case, make it virtual, it's always a good habit.)

Array of int at the output of a mex file

I am trying to create a mex function whose entry is an integer and whose output is an array of integer.
So the function looks like: int *myFunction(unsigned int N).
In the mexFunction, I declare a variable *variab of type int and then
N = mxGetScalar(prhs[0]);
/* assign a pointer to the output */
siz= 2*ceil(log(1.0*N)/log(2.0)-0.5)+1;
plhs[0] = mxCreateDoubleMatrix(1,siz, mxREAL);
vari = (int*) mxGetPr(plhs[0]); */
/* Call the subroutine. */
vari = myFunction(N);
mexPrintf("The first value is %d\n", vari[0]);
The thing is the first value is the correct one (and the other ones were checked and were correct as well) but when I call the routine mxFunction(16), I get only 0's as output.
I guess it is because my output is an array of int but I don't know how to solve the problem. Any hint?
Cheers.
Matlab deals with doubles by default. You can easily cast them in your mex function like the following example based on your code snippet. I have made a myFunction that performs a demo algorithm. Rather than return a data type, I make it a void function and pass it a pointer to the output so that it can populate it . . .
/*************************************************************************/
/* Header(s) */
/*************************************************************************/
#include "mex.h"
#include "math.h"
/*************************************************************************/
/*the fabled myFunction */
/*************************************************************************/
void myFunction(unsigned int N, unsigned int siz, double* output)
{
int sign = 1;
for(int ii=0; ii<siz; ++ii)
{
output[ii] = (double)(ii * sign + N);
sign *= -1;
}
}
/*************************************************************************/
/* Gateway function and error checking */
/*************************************************************************/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
/* variable declarations */
unsigned int siz;
double N;
/* check the number of input and output parameters */
if(nrhs!=1)
mexErrMsgTxt("One input arg expected");
if(nlhs > 1)
mexErrMsgTxt("Too many outputs");
N = mxGetScalar(prhs[0]);
/* assign a pointer to the output */
siz= 2*ceil(log(1.0*N)/log(2.0)-0.5)+1;
plhs[0] = mxCreateDoubleMatrix(1,siz, mxREAL);
myFunction(N, siz, mxGetPr( plhs[0]) );
}

Mex file gives segmentation fault only on second use

The following code compiles successfully and returns the correct results when called the first time. Making the same call a second time, I get a segmentation fault error.
//% function TF = InWindow(Date,WindowStartDates,WindowEndDates,EndHint)
//% INWINDOW returns true for window that contains Date. All inputs must be
//% uint32 and WindowEndDates must be sorted.
//% EndHint is an optional input that specifies the row number to start
//% searching from.
#include "mex.h"
#include "matrix.h"
#include "math.h"
void CalculationRoutine(mxLogical *ismember, uint32_T *Date, uint32_T *WindowStartDates, uint32_T *WindowEndDates, unsigned int *StartIndex, int NumObs) {
mwIndex Counter;
// Find the first window that ends on or after the date.
for (Counter = (mwIndex) *StartIndex; Counter < NumObs; Counter++) {
if (*Date <= *(WindowEndDates+Counter)) {
break;
}
}
*StartIndex = (unsigned int) Counter;
// Now flag every observation within the window. Remember that WindowStartDates
// is not necessarily sorted (but WindowEndDates is).
for (Counter = (mwIndex) *StartIndex; Counter < NumObs; Counter++) {
if (*Date >= *(WindowStartDates+Counter)) {
*(ismember+Counter) = true;
}
}
}
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) {
mxArray *ismember;
unsigned int *StartIndex;
//Input Checking.
if (nrhs == 3) {
// Default Hint to first entry.
mexPrintf("SI Starts OK.\n");
*StartIndex = 1;
mexPrintf("SI Ends OK.\n");
} else if (nrhs == 4) {
if (!mxIsUint32(prhs[3])) {
mexErrMsgTxt("EndHint must be uint32.");
}
StartIndex = mxGetData(prhs[3]);
} else {
mexErrMsgTxt("Must provide three or four input arguments.");
}
// Convert the hint to base-zero indexing.
*StartIndex = *StartIndex - 1;
// Check the inputs for the window range.
if (!mxIsUint32(prhs[0])) {
mexErrMsgTxt("DatesList must be uint32.");
}
if (!mxIsUint32(prhs[1])) {
mexErrMsgTxt("WindowStartsDates must be uint32.");
}
if (!mxIsUint32(prhs[2])) {
mexErrMsgTxt("WindowEndsDates must be uint32.");
}
if (mxGetM(prhs[1]) != mxGetM(prhs[2])) {
mexErrMsgTxt("WindowStartDates must be the same length as WindowEndDates.");
}
// Prepare the output array.
ismember = mxCreateLogicalArray(mxGetNumberOfDimensions(prhs[1]), mxGetDimensions(prhs[1]));
CalculationRoutine(mxGetLogicals(ismember),mxGetData(prhs[0]),
mxGetData(prhs[1]), mxGetData(prhs[2]), StartIndex, (int) mxGetM(prhs[1]));
plhs[0] = ismember;
}
I call it with:
>>InWindow(uint32(5),uint32((1:6)'),uint32((3:8)'))
The code reaches the line between the two mexPrintf calls before the segmentation fault (ie the first call prints, but not the second).
I am on Matlab 2007a (yes, I know), Win7 64bit and VS 2008.
You need to initialize the pointer StartIndex - you're "lucky" that it works the first time, since it is not pointing to a defined memory location. Why not do something more like:
unsigned int StartIndex;
// and either:
StartIndex = 1;
// or:
StartIndex = * (static_cast< unsigned int * >( mxGetData(prhs[3]) ) );