I need to write a c++ program with these objectives - c++

A C++ program which read data from a text file. Suppose text file contains a
paragraph about any topic. Your program asks user to enter file name without extension. Now, a
user defined function (name: ReadWordByWord()) reads all data word by word and store in a
character type array with dynamically grows according to the data.
Finally, declare a user-defined function (name: SaveInReverse()) which stores this text into a
text file (name is entered by user) in reverse order of words e.g. last words will be stored at start,
then 2nd last word, 3rd last word etc. of the original document.
And here is what I've done so far... Here I am not using the delete command, that if I use will cause an error- a heap error. How can I accomplish that first? And then what are any tips to improve this program.
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
char* readWordByWord(char * old)
{
int coun = 0;
for (int i = 0; old[i] != '\0'; i++) // to find the length of word
{
coun++;
}
char *newArr = new char[coun + 1];
strcpy(newArr, old);
//delete[]old; // this is where i am putting delete command to delete the previous i.e old array and then return the new one
return newArr;
}
int size = 100;
int main()
{
fstream fin;
string forCopy[1000];
int index = 0;
fin.open("file.txt");
char *p = new char[size];
while (fin >> p)
{
p = readWordByWord(p);
//cout << p<<endl;
forCopy[index++] = p;
/*for (int i = 0; p[i] != '\0'; i++)
{
}*/
}
for (int i = index - 1; i > 0; i--)
cout << forCopy[i] << " ";
delete[]p;
p = NULL;
fin.close();
return 0;
}

I've made it from start again (must not include newlines since only a paragraph required):
#include <iostream>
#include <fstream>
#include <string>
void reverse(char *begin, char *end) { // reverses a word
char temp;
while (begin < end) {
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
void reverseParagraph(char *arg) { // reverses each word of the paragraph
char *word_begin = arg;
char *temp = arg;
while (*temp) {
temp++;
if (*temp == '\0')
reverse(word_begin, temp - 1);
else if (*temp == ' ') {
reverse(word_begin, temp - 1);
word_begin = temp + 1;
}
}
reverse(arg, temp - 1);
}
int main() {
std::ifstream file("file.txt");
std::string fileData = "";
while(getline(file, fileData)); // counting the number of letters for memory allocation
size_t len = fileData.length();
char *str = new char[len + 1];
strcpy(str, fileData.c_str());
reverseParagraph(str); // reverse the entire character pointer
std::cout << str << std::endl; // displays for testing
std::ofstream fileOut("out.txt");
fileOut << str << std::endl; // saving the output into another file
fileOut.close();
delete[] str;
file.close();
return 0;
}
This program firstly gets the containing data of a file and then assigns into a variable. The variable is then converted into character (pointer) after getting the string length.
After that, it recursively reverses the position each word of the fileData and finally it displays. The modified data is thereafter printed into another file.

Related

C++: English to Pig Latin

I am receiving an error from the following code when I try to dynamically allocate the array (seen after my attempt to incrementing through each letter in the users array using the bool function). This is the error:
main.cpp: In function ‘Word* splitSentene(std::string, int&)’:
main.cpp:81:32: error: cannot convert ‘std::string* {aka std::basic_string*}’ to ‘Word*’ in assignment
words = new string[i];
I am trying to count how many words the user inputs and dynamically allocate an array for the string of words. This is my code thus far:
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
struct Word
{
string english; // English sentence
string piglatin; // Pig latin sentence
};
// PT 1. Function prototype
Word * splitSentence(const string words, int &size){};
int main()
{
string userSentence;
int size;
// Get the users sentence to convert to pig latin
cout << "Please enter a string to convert to pig latin:\n";
getline(cin, userSentence);
// Directs to Word * splitSentence function
Word* tempptr = splitSentence(userSentence, size);
delete [] tempptr;
return 0;
}
//PT 1. Analyze the sentence
Word * splitSentene(const string words, int &size)
{
bool flag = true;
int num = 0;
for (int i = 0; i < words.length() + 1; i++)
{
//test for white space, then when you hit the first alphabetical character after a space,
//increment up the size of the array
if (isspace(words[i]))
flag = true;
if (isalpha(words[i]));
{
if (flag == true)
{
flag = false;
cout << words[i++];
}
}
// Dynamically allocate the array for the words
Word *sentence = nullptr;
sentence = new string[i];
}
}
Here are the pt 1 instructions for further clarification:
PT. 1) Write a function that takes in an English sentence as one string. This function should first calculate how many “words” are in the sentence (words being substrings separated by whitespace). It should then allocate a dynamic array of size equal to the number of words. The array contains Word structures (i.e. array of type Word). The function would then store each word of that sentence to the english field of the corresponding structure. The function should then return this array to the calling function using the return statement, along with the array size using a reference parameter.
This function should also remove all capitalization and special characters other than letters. Implement the function with the following prototype:
Word * splitSentence(const string words, int &size);
This is my first post here, so I will appreciate any input on how to dynamically allocate the array and format it (if I have successfully coded how to count the words in the sentence the user inputs). If more information needs to be provided, let me know!
The compiler error is because you are trying to assign a string[] array to a Word* pointer. You need to allocate a Word[] array instead.
You also have other errors in your code:
You have an erroneous {} at the end of the declaration of splitSentence().
You misspelled splitSentene in the defintion of splitSentence().
You have an erroneous ; on if (isalpha(words[i]));
You are not return'ing the array that you allocate.
In fact, you are not even following the instructions properly at all. You are not "calculating how many words are in the sentence" BEFORE allocating the array (you tried, but you are doing the allocation in the wrong place), and you are not filling the array at all, let alone "removing all capitalization and special characters other than letters".
Try something more like this:
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
struct Word
{
string english; // English sentence
string piglatin; // Pig latin sentence
};
// PT 1. Function prototype
Word* splitSentence(const string words, int &size);
int main()
{
string userSentence;
int size;
// Get the users sentence to convert to pig latin
cout << "Please enter a string to convert to pig latin:\n";
getline(cin, userSentence);
// Directs to Word * splitSentence function
Word* tempptr = splitSentence(userSentence, size);
delete [] tempptr;
return 0;
}
//PT 1. Analyze the sentence
Word* splitSentence(const string words, int &size)
{
bool flag = true;
int num = 0;
char ch;
for (int i = 0; i < words.length(); ++i)
{
ch = words[i];
if (isalpha(ch))
{
if (flag)
{
flag = false;
++num;
}
}
else if (isspace(ch))
{
flag = true;
}
}
Word *sentence = new Word[num];
int index = -1;
flag = true;
num = 0;
for (int i = 0; i < words.length(); ++i)
{
ch = words[i];
if (isalpha(ch))
{
if (flag)
{
flag = false;
++num;
++index;
}
if (isupper(ch))
{
ch = tolower(ch);
}
sentence[index].english += ch;
}
else if (isspace(ch))
{
flag = true;
}
}
size = num;
return sentence;
}
Live Demo
That being said, this will be much easier to implement splitSentence() if you could use std::istringstream and std::vector and other C++ idioms, instead of using C idioms, eg:
#include <iostream>
#include <sstream>
#include <cctype>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Word
{
string english; // English sentence
string piglatin; // Pig latin sentence
};
// PT 1. Function prototype
Word* splitSentence(const string words, int &size);
int main()
{
string userSentence;
int size;
// Get the users sentence to convert to pig latin
cout << "Please enter a string to convert to pig latin:\n";
getline(cin, userSentence);
// Directs to Word * splitSentence function
Word* tempptr = splitSentence(userSentence, size);
delete [] tempptr;
return 0;
}
//PT 1. Analyze the sentence
Word* splitSentence(const string words, int &size)
{
istringstream iss(words);
vector<string> vec;
string s;
while (iss >> s)
{
remove_if(s.begin(), s.end(),
[](unsigned char ch){ return !isalpha(ch); });
if (!s.empty())
{
transform(s.begin(), s.end(), s.begin(),
[](unsigned char ch){ return tolower(ch); });
vec.push_back(s);
}
}
Word *sentence = new Word[vec.size()];
transform(vec.begin(), vec.end(), sentence,
[](const string &s){
Word w;
w.english = s;
return w;
}
);
size = vec.size();
return sentence;
}
Live Demo

How to split a string by another string in Arduino?

I have a character array like below:
char array[] = "AAAA... A1... 3. B1.";
How can I split this array by the string "..." in Arduino? I have tried:
ptr = strtok(array, "...");
and the output is the following:
AAAA,
A1,
3,
B1
But I actually want output to be
AAAA,
A1,
3.B1.
How to get this output?
edit:
My full code is this:
char array[] = "AAAA... A1... 3. B1.";
char *strings[10];
char *ptr = NULL;`enter code here`
void setup()
{
Serial.begin(9600);
byte index = 0;
ptr = strtok(array, "..."); // takes a list of delimiters
while(ptr != NULL)
{
strings[index] = ptr;
index++;
ptr = strtok(NULL, "..."); // takes a list of delimiters
}
for(int n = 0; n < index; n++)
{
Serial.println(strings[n]);
}
}
The main problem is that strtok does not find a string inside another string. strtok looks for a character in a string. When you give multiple characters to strtok it looks for any of these. Consequently, writing strtok(array, "..."); is exactly the same as writing strtok(array, ".");. That is why you get a split after "3."
There are multiple ways of doing what you want. Below I'll show you an example using strstr. Unlike strtokthe strstr function do find a substring inside a string - just what you are looking for. But.. strstr is not a tokenizer so some extra code is required to print the substrings.
Something like this should do:
int main()
{
char array[] = "AAAA... A1... 3. B1...";
char* ps = array;
char* pf = strstr(ps, "..."); // Find first substring
while(pf)
{
int len = pf - ps; // Number of chars to print
printf("%.*s\n", len, ps);
ps = pf + 3;
pf = strstr(ps, "..."); // Find next substring
}
return 0;
}
You can implement your own split as strtok except the role of the second argument :
#include <stdio.h>
#include <string.h>
char * split(char *str, const char * delim)
{
static char * s;
char * p, * r;
if (str != NULL)
s = str;
p = strstr(s, delim);
if (p == NULL) {
if (*s == 0)
return NULL;
r = s;
s += strlen(s);
return r;
}
r = s;
*p = 0;
s = p + strlen(delim);
return r;
}
int main()
{
char s[] = "AAAA... A1... 3. B1.";
char * p = s;
char * t;
while ((t = split(p, "...")) != NULL) {
printf("'%s'\n", t);
p = NULL;
}
return 0;
}
Compilation and execution:
/tmp % gcc -g -pedantic -Wextra s.c
/tmp % ./a.out
'AAAA'
' A1'
' 3. B1.'
/tmp %
I print between '' to show the return spaces, because I am not sure you want them, so delim is not only ... in that case
Because you tagged this as c++, here is a c++ 'version' of your code:
#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;
#include <string>
using std::string;
class T965_t
{
string array;
vector<string> strings;
public:
T965_t() : array("AAAA... A1... 3. B1.")
{
strings.reserve(10);
}
~T965_t() = default;
int operator()() { return setup(); } // functor entry
private: // methods
int setup()
{
cout << endl;
const string pat1 ("... ");
string s1 = array; // working copy
size_t indx = s1.find(pat1, 0); // find first ... pattern
// start search at ---------^
do
{
if (string::npos == indx) // pattern not found
{
strings.push_back (s1); // capture 'remainder' of s1
break; // not found, kick out
}
// else
// extract --------vvvvvvvvvvvvvvvvv
strings.push_back (s1.substr(0, indx)); // capture
// capture to vector
indx += pat1.size(); // i.e. 4
s1.erase(0, indx); // erase previous capture
indx = s1.find(pat1, 0); // find next
} while(true);
for(uint n = 0; n < strings.size(); n++)
cout << strings[n] << "\n";
cout << endl;
return 0;
}
}; // class T965_t
int main(int , char**) { return T965_t()(); } // call functor
With output:
AAAA
A1
3. B1.
Note: I leave changing "3. B1." to "3.B1.", and adding commas at end of each line (except the last) as an exercise for the OP if required.
I looked for a split function and I didn't find one that meets my requirement, so I made one and it works for me so far, of course in the future I will make some improvements, but it got me out of trouble.
But there is also the strtok function and better use that.
https://www.delftstack.com/es/howto/arduino/arduino-strtok/
I have the split function
Arduino code:
void split(String * vecSplit, int dimArray,String content,char separator){
if(content.length()==0)
return;
content = content + separator;
int countVec = 0;
int posSep = 0;
int posInit = 0;
while(countVec<dimArray){
posSep = content.indexOf(separator,posSep);
if(posSep<0){
return;
}
countVec++;
String splitStr = content.substring(posInit,posSep);
posSep = posSep+1;
posInit = posSep;
vecSplit[countVec] = splitStr;
countVec++;
}
}
Llamada a funcion:
smsContent = "APN:4g.entel;DOMAIN:domolin.com;DELAY_GPS:60";
String vecSplit[10];
split(vecSplit,10,smsContent,';');
for(int i = 0;i<10;i++){
Serial.println(vecSplit[i]);
}
String input:
APN:4gentel;DOMAIN:domolin.com;DELAY_GPS:60
Output:
APN:4g.entel
DOMAIN:domolin.com
DELAY_GPS:60
RESET:true
enter image description here

Shifting an array of structs C++

I am quite new to c++ programming and data structures and really need some help. I am working on an assignment where I have a text file with 100 lines and on each line there is an item, a status(for sale or wanted), and a price. I need to go through the text file and add lines to an array of structs and as I add lines I need to compare the new information with the previously submitted information. If there is a line that is wanted and has a price higher than a previously input item that is for sale then the item would be removed from the struct and the array of structs shifted.
The place that I am having trouble is in actually shifting all the structs once a line that satisfies the condition is found.
My issue is that when I try to shift the array of structs using the second for loop nothing happens and I just get null structs and nothing seems to move.
Please if you guys can offer any help it would be greatly appreciated.
Below is the code of the text file and my current code.
#include<iostream>
#include<fstream>
#include <string>
#include <algorithm>
#include <sstream>
using namespace std;
struct items
{
string type;
int status;
int price;
} itemArray [100];
int main(int argc, char *argv[]) {
int x = -1;
//int chickenCount = 0;
int counter = 0;
int itemsSold = 0;
int itemsRemoved = 0;
int itemsForSale = 0;
int itemsWanted = 0;
string itemType;
int itemStatus = 0;
int itemPrice = 0;
int match = 0;
ifstream myReadFile( "messageBoard.txt" ) ;
std::string line;
//char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
getline(myReadFile,line); // Saves the line in STRING.
line.erase(std::remove(line.begin(), line.end(), ' '), line.end());
//cout<<line<<endl; // Prints our STRING.
x++;
std::string input = line;
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
counter++;
//std::cout << token << '\n';
if (counter>3){
counter =1;
}
//cout << x << endl;
if (counter == 1){
itemType = token;
//cout<< itemType<<endl;
}
if (counter == 2){
if (token == "forsale"){
itemStatus = 1;
//itemsForSale++;
}
if (token == "wanted"){
itemStatus = 0;
//itemsWanted++;
}
//cout<< itemStatus<<endl;
}
if (counter == 3){
itemPrice = atoi(token.c_str());
//cout<< itemPrice<<endl;
}
//cout<<"yo"<<endl;
}
if (x >= 0){
for (int i = 0; i<100;i++){
if (itemArray[i].type == itemType){
//cout<<itemType<<endl;
if(itemArray[i].status != itemStatus){
if (itemArray[i].status == 1){
if(itemPrice>=itemArray[i].price){
itemsSold++;
match =1;
//itemArray[i].type = "sold";
for (int j=i; j<100-1;j++){
//cout<<j<<endl;
itemArray[j].type = itemArray[j+1].type;
itemArray[j].status = itemArray[j+1].status;
itemArray[j].price = itemArray[j+1].price;
}
i =i-1;
break;
}
}
if (itemArray[i].status == 0){
if(itemArray[i].price>=itemPrice){
itemsSold++;
match = 1;
//itemArray[i].type = "sold";
for (int j=i; j<100-1;j++){
//cout<<j<<endl;
itemArray[j].type = itemArray[j+1].type;
itemArray[j].status = itemArray[j+1].status;
itemArray[j].price = itemArray[j+1].price;
}
i=i-1;
break;
}
}
}
}
}
}
if (counter == 3 && match == 0){
itemArray[(x)].type = itemType;
itemArray[(x)].status = itemStatus;
itemArray[(x)].price = itemPrice;
}
match = 0;
// cout << itemArray[x].type << " " << itemArray[x].status<<" "<<itemArray[x].price<<endl;
}
for(int i=0;i<100;i++){
cout<<itemArray[i].type<< " "<<itemArray[i].status<<" "<<itemArray[i].price<<endl;
}
//cout<<itemArray[1].price<<endl;
cout << itemsSold<<endl;
}
myReadFile.close();
return 0;
}
text file: https://drive.google.com/file/d/0B8O3izVcHJBzem0wMzA3VHoxNk0/view?usp=sharing
Thanks for the help
I see several issues in the code, but without being able to test it, I think the main problem is that you always insert new elements at position 'x' which correspond to the currently line read from the file, without taking into account any shift of elements done. You should insert the new element at the first empty slot (or just overwrite the old element instead of shifting everything).
An other issue is that you do not initialize the status and price in your array.
The best way would be to rewrite the code by using more standard C++ features, for example:
replace the items structure by a class with a constructor defining default values
use object copy (there is no need to copy a struct element by element)
use standard C++ containers like a list (see http://www.cplusplus.com/reference/list/list/) which has insert and erase methods

Simple read from text file algorithm doesn't work

I have a text file that contains keys and values like this:
keyOne=1
keyTwo=734
keyThree=22.3
keyFour=5
The keys are just lower-case and upper-case letters like in my example. The values are either integers or floats. Each key and value is separated by an equals sign (=). Now I want to read the values into variables I have in my program.
This is the code I have tried to read the values:
(I omitted the part where I store the values in my program's variables, and just print them out now for demonstration.)
std::fstream file(optionsFile, std::fstream::in);
if (file.good()) {
int begin;
int end;
std::string line;
while(std::getline(file, line)) {
// find the position of the value in the line
for (unsigned int i = 0; i < line.length(); i++) {
if (line.at(i) == '=') {
begin = i + 1;
end = line.length();
break;
}
}
// build the string... it starts at <begin> and ends at <end>
const char *string = "";
for (int i = begin; i < end; i++) {
string += line.at(i);
}
// only gibberish is printed in the following line :(
std::cout << "string=" << string << std::endl;
}
}
I don't understand why it won't print the value.. instead only weird stuff or even nothing is printed
Please help this broke my spirit so hard :(
You are using C-style strings (char arrays) without properly allocated memory, and you are just manipulating with the pointer, so you are not appending characters into your string:
// build the string... it starts at <begin> and ends at <end>
const char *string = "";
for (int i = begin; i < end; i++) {
string += line.at(i);
}
Use std::string instead:
/// build the string... it starts at <begin> and ends at <end>
std::string str;
for (int i = begin; i < end; i++) {
str += line.at(i);
}
Or allocate memory by hand, use the proper indexing, terminate the string with '\0' character and don't forget to delete the string after you don't need it anymore:
char *string = new char[end - begin + 1];
int j = 0;
for (int i = begin; i < end; i++) {
string[j++] = line.at(i);
}
// Don't forget to end the string!
string[j] = '\0';
// Don't forget to delete string afterwards!
delete [] string;
So, just use std::string.
Edit Why did you mix C strings and std::string in the first place?
As was already mentioned, native string types in c/c++ do not support straightforward concatenation since they are essentially pointers to some preallocated memory. You should always use std::string when a string is supposed to be mutable.
Btw, think about the following refactoring:
void process_option (const std::string& a_key, const std::string& a_value)
{
std::cout << a_key << " <-- " << a_value << std::endl;
}
void read_options (std::istream& a_in, const char* a_source)
{
int line_n = 0;
std::string line;
while (std::getline(a_in, line))
{
++ line_n;
std::string::size_type p = line. find('=');
if (p == line. npos)
{
// invalid_entry(a_source, line_n);
continue;
}
process_option(
line. substr(0, p), // key
line. substr(p + 1, line. find_first_of("\t\r\n", p + 1)) // value
);
}
}
void read_options (const char* a_filename)
{
std::ifstream file(a_filename);
if (! file)
{
// read_error(a_filename);
return;
}
read_options(file, a_filename);
file. close();
}
void read_options (const std::string& a_filename)
{
read_options(a_filename. c_str());
}

I get a number 2 when I reverse my string

I wrote this code to reverse strings. It works well, but when I enter short strings like "american beauty," it actually prints "ytuaeb nacirema2." This is my code. I would like to know what is wrong with my code that prints a random 2 at the end of the string. Thanks
// This program prompts the user to enter a string and displays it backwards.
#include <iostream>
#include <cstdlib>
using namespace std;
void printBackwards(char *strPtr); // Function prototype
int main() {
const int SIZE = 50;
char userString[SIZE];
char *strPtr;
cout << "Please enter a string (up to 49 characters)";
cin.getline(userString, SIZE);
printBackwards(userString);
}
//**************************************************************
// Definition of printBackwards. This function receives a *
// pointer to character and inverts the order of the characters*
// within it. *
//**************************************************************
void printBackwards(char *strPtr) {
const int SIZE = 50;
int length = 0;
char stringInverted[SIZE];
int count = 0;
char *strPtr1 = 0;
int stringSize;
int i = 0;
int sum = 0;
while (*strPtr != '\0') {
strPtr++; // Set the pointer at the end of the string.
sum++; // Add to sum.
}
strPtr--;
// Save the contents of strPtr on stringInverted on inverted order
while (count < sum) {
stringInverted[count] = *strPtr;
strPtr--;
count++;
}
// Add '\0' at the end of stringSize
stringInverted[count] == '\0';
cout << stringInverted << endl;
}
Thanks.
Your null termination is wrong. You're using == instead of =. You need to change:
stringInverted[count] == '\0';
into
stringInverted[count] = '\0';
// Add '\0' at the end of stringSize
stringInverted[count] == '\0';
Should use = here.
What is wrong with your code is that you do not even use strlen for counting the length of the string and you use fixed size strings (no malloc, or, gasp new[]), or the std::string (this is C++)! Even in plain C, not using strlen is always wrong because it is hand-optimized for the processor. What is worst, you have allocated the string to be returned (stringInverted) from the stack frame, which means when the function exits, the pointer is invalid and any time the code "works" is purely accidental.
To reverse a string on c++ you do this:
#include <iostream>
#include <string>
int main() {
std::string s = "asdfasdf";
std::string reversed (s.rbegin(), s.rend());
std::cout << reversed << std::endl;
}
To reverse a string in C99 you do this:
char *reverse(const char *string) {
int length = strlen(string);
char *rv = (char*)malloc(length + 1);
char *end = rv + length;
*end-- = 0;
for ( ; end >= rv; end --, string ++) {
*end = *string;
}
return rv;
}
and remember to free the returned pointer after use. All other answers so far are blatantly wrong :)