Reversing a string using only iostream, fstream, string and vector - c++11

I just started working with C++ about a week ago so I don't know much about the language. I am working on creating a program that inputs a text file and then reverses all of the lines.
So an input of:
"abc"
"123"
Would be:
"cba"
"321"
I can figure out how to input the lines from the file, but I am having trouble with my reverse function. I have tried to just print out each individual character as a string using substring, starting from length - 1 and ending at 0. But this does not seem to be working. When I run the program, I get these errors that I don't understand.. Any ideas as to what is going wrong?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void reverse(string input) {
for((int x=input.length()-1); x=0; x--)
cout << input.substr(x);
}
cout << endl;
}
int main()
{
string line;
ifstream myFile;
myFile.open("reverse_input.txt");
while(getline(myFile, line)) {
reverse(line);
}
return 0;
}

There are couple syntax errors in your code that the compiler was complaining
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void reverse(string input) {
for( unsigned int x= (input.length()-1); x>=0; x--) { //Missing {, extra (), >= insteadof = 0
cout << input[x] << flush;
}
cout << endl;
}
int main()
{
string line;
ifstream myFile;
myFile.open("reverse_input.txt");
while(getline(myFile, line)) {
reverse(line);
}
return 0;
}

Related

Using recursion inside a called constructor

Don't know where to begin on how to use recursion within a called constructor.
recursion.cpp
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
#include "MinilabRecursion.h"
MinilabRecursion::puzzleRecurse(int n)
{
int recurse(n) // <--- Don't know what to do here
{ //error: expected ',' or ';' before '{' token
if( n == 0 )
{
return 1;
}
if( n >= 1 )
{
return recurse(n - 1) + 4 * n;
}
}
} //error: expected '}' at end of input
driver.cpp
#include <iostream>
#include <string>
using namespace std;
#include "MinilabRecursion.h"
{
cout << "puzzleRecurse(1) returns: " << MinilabRecursion::puzzleRecurse(1) << endl;
cout << "puzzleRecurse(7) returns: " << MinilabRecursion::puzzleRecurse(7) << endl;
cin.get();
return 0;
}
recursion.h
#ifndef MINILABRECURSION_H
#define MINILABRECURSION_H
#include <iostream>
#include <string>
using namespace std;
class MinilabRecursion
{
public:
static int puzzleFormula(int n);
static int puzzleLoop(int n);
static int puzzleRecurse(int n);
};
#endif
The if statements within recursion.cpp should give me the desired outcome, but I do not know how to use recursion in this context.
I'm not sure I can make sense out of the code you posted. It seems you want to do the following, but are confused about some of the C++ basics:
int MinilabRecursion::puzzleRecurse(int n)
{
if (n == 0) {
return 1;
}
return puzzleRecurse(n - 1) + 4 * n;
}

The problem is i need the input of the string to accept a blank line

The program is supposed to receive a string, that can have blank lines, blank spaces, and break lines. So the problem is i can't use get line, because i don't know how many break lines the user will use.
I tried making a do while but it didn't work, the program stops working.
It was a do while, that would receive an char and using pushback insert in the string while the char was different to EOF. I don't know how else to do it, or why this do while doesn't work.
This code is using get line witch doesn't accept a break line.
'''''
#ifndef INDICE_H
#define INDICE_H
#include <cstddef>
struct Indice{
std::size_t f;
double p;
};
#endif
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <map>
#include "Indice.hpp"
int main()
{
std::string str;
std::getline(std::cin, str);
// Count the number of occurrences for each word
std::string word;
std::istringstream iss(str);
std::map<std::string,Indice> occurrences;
while (iss >> word) ++occurrences[word].f;
//Calculate the percentual each word
int total = 0.0;
for (std::map<std::string,Indice>::iterator it = occurrences.begin();
it != occurrences.end(); ++it)
{
total += it->second.f;
}
for (std::map<std::string,Indice>::iterator it = occurrences.begin();
it != occurrences.end(); ++it)
{
it->second.p = (static_cast<double>(it->second.f))/total;
}
// Print the results
for (std::map<std::string,Indice>::iterator it = occurrences.begin();
it != occurrences.end(); ++it)
{
if(it->first.size()>2)
std::cout << it->first << " " << it->second.f << " "<< std::fixed << std::setprecision(2) << it->second.p << std::endl;
}
return 0;
}
''''
Two possible solutions:
#include <iostream>
#include <string>
int main(){
std::string line;
while(std::cin >> line){
//Variable line contains your input.
}
//Rest of your code
return 0;
}
Or:
#include <iostream>
#include <string>
int main(){
std::string line;
while(std::getline(std::cin, line)){
if (line.empty()){
break;
}
//Variable line contains your input.
}
//Rest of your code
return 0;
}

Boost::spirit::qi - How do I build a parse rule that sets a property?

I'd like to build a rule that takes in a few parameters from a parsed line then sets a few as constant. Is that possible? An (invalid) example to illustrate what I'm trying to do is below. I think I'm using _r1 incorrectly here, but I'm not sure how to get at the right thing. Assume I don't want to just modify r before sending it into the parser.
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_plus.hpp>
#include <boost/spirit/include/qi_sequence.hpp>
#include <boost/spirit/include/qi_string.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/phoenix/bind/bind_function.hpp>
#include <string>
using namespace boost::spirit::qi;
struct Sample
{
int a;
int b;
};
BOOST_FUSION_ADAPT_STRUCT(Sample, a , b)
const rule<std::string::const_iterator, Sample()> AnythingAndOne = int_ >> eps[_r1.b = 1] >> eoi;
int main()
{
std::string z("3");
Sample r;
parse(z.begin(), z.end(), AnythingAndOne, r);
return 0;
}
Again, with reference to Boost Spirit: "Semantic actions are evil"? I'd avoid the semantic action.
You can directly synthesize a particular attribute value by using qi::attr:
Live On Coliru
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
struct Sample {
int a;
int b;
};
BOOST_FUSION_ADAPT_STRUCT(Sample, a , b)
namespace qi = boost::spirit::qi;
int main()
{
std::string const z("3");
Sample r;
qi::rule<std::string::const_iterator, Sample()> AnythingAndOne
= qi::int_ >> qi::attr(1) >> qi::eoi;
if (parse(z.begin(), z.end(), AnythingAndOne, r))
std::cout << "Parsed: " << boost::fusion::as_vector(r) << "\n";
else
std::cout << "Parse failed\n";
}
Prints
Parsed: (3 1)

Search Function returns wrong results

I have made a function for my program that reads from a text file, adds content to a vector and then search in that vector. The Problem is that even if the file is empty it shows that it found something, on the other side if i change return value to 0 it does not give results at all!
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
vector<string> contacts;
//This function returns at what index the name is found
int searchContact(string contactToSearch)
{
string entry;
ifstream input;
input.open("contacts.txt");
while (input.good())
{
while (getline(input, entry))
{
contacts.push_back(entry);
}
input.close();
}
for(int i = 0; i < contacts.size(); i++)
{
if(contactToSearch == contacts[i])
{
//Found => Returning index rest of program can see index
return i;
}
}
return 1;
}
I have just refactored your code a little. Further improvements are possible, but to begin with
1) You dont need a while for input.good()
2) You were trying to return 0 and 1 which are indeed valid positions where the string could have been present in the vector
All these aside, I still think your code might not properly populated the array The reasons for this maybe :- case sensitive comparison, reading incorrect file, binary file.. etc..
Here is a refactored code that you could use
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
void readContacts(const string &fileName inputFileName, vector<string> &contacts){
string entry;
ifstream input;
input.open(inputFileName);
if (input.good())
{
while (getline(input, entry))
contacts.push_back(entry);
input.close();
}
}
int searchContact(const string &contactToSearch, vector<string> &contacts)
{
for (int i = 0; i < contacts.size(); i++)
{
if (contactToSearch == contacts[i])
return i;
}
return -1;
}
int main(){
vector<string> contacts;
// This needs to be filled in with the contact name u want to search
string contactToSearch;
readContacts("contacts.txt", contacts);
int index = searchContact(contactToSearch, contacts)
if (index != -1)
cout << "Found Contact " << contactToSearch" at location " << index << endl;
else
cout << "Could Not find contact " << contactToSearch << endl;
}

Interleave random numbers

I would like to interleave a random number with some alphanumeric characters, for example: HELLO mixed with the random number 25635 → H2E5L6L3O5. I know %1d controls the spacing, although I'm not sure how to interleave text between the random numbers or how accomplish this.
Code:
int main(void) {
int i;
srand(time(NULL));
for (i = 1; i <= 10; i++) {
printf("%1d", 0 + (rand() % 10));
if (i % 5 == 0) {
printf("\n");
}
}
return 0;
}
btw - if my random number generator isn't very good i'm open to suggestions - thanks
If you're okay with using C++11, you could use something like this:
#include <iostream>
#include <random>
#include <string>
int main() {
std::random_device rd;
std::default_random_engine e1(rd());
std::uniform_int_distribution<int> uniform_dist(0, 9);
std::string word = "HELLO";
for (auto ch : word) {
std::cout << ch << uniform_dist(e1);
}
std::cout << '\n';
}
...which produces e.g.:
H3E6L6L1O5
If you're stuck with an older compiler, you could use rand and srand from the standard C library for your random numbers:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
int main() {
std::srand(std::time(NULL));
std::string word = "HELLO";
for (int i = 0; i < word.size(); ++i) {
std::cout << word[i] << (rand() % 10);
}
std::cout << '\n';
}

Resources