That's my first question here, so I would be glad to receive some support on the style I used to refer to my problem :). Here is the finished program, its main purpose is to split given words into halves and create words replacing the origin ones. Replaced words are build from its origins by spliting them into halves and taking even ones from the 1st half begining with the first letter of a word. Heres the complete code:
#include <iostream>
#include <string>
#include <cstdio>
#include <math.h>
using namespace std;
void obcinaczSlow(int);
int main(){
int ilosc;
cout << "Prosze o podanie ilosci prob: ";
cin>>ilosc;
cout << endl;
obcinaczSlow(ilosc);
cin.ignore();
cin.get();
return 0;
}
void obcinaczSlow(int ilosc_prob){
int i=0,j=0,dlugosc_slowa=0,dlugosc_polowy=0;
string *tablica_slow,budowane_slowo,aktualne_slowo,dodane;
tablica_slow = new string [ilosc_prob];
cout << "Prosze o podanie " << ilosc_prob << " slow" << endl;
cin.sync();
for(i=0;i<ilosc_prob;i++){
cout << "Prosze o podanie slowa numer: " << i+1 << endl;
cin>>aktualne_slowo;
tablica_slow[i] = aktualne_slowo;
}
for(i=0;i<ilosc_prob;i++){
aktualne_slowo = tablica_slow[i];
cout << "Aktualne slowo do przerobienia: " << aktualne_slowo << endl;
dlugosc_slowa = aktualne_slowo.length();
cout << "Dlugosc slowa do przerobienia: " << dlugosc_slowa << endl;
dlugosc_polowy = floor(dlugosc_slowa/2);
cout << "Dlugosc polowy slowa int: " << dlugosc_polowy << endl;
budowane_slowo.clear();
dodane.clear();
cout << "Budowane slowo to: " << budowane_slowo << endl;
for(j=0;j<=dlugosc_polowy;j=+2){
dodane = aktualne_slowo.at(j);
budowane_slowo.append(dodane);
}
tablica_slow[i] = budowane_slowo;
}
cout << "Slowa po transformacji wygladaja nastepujaco: " << endl;
for(i=0;i<ilosc_prob;i++){
cout << "Slowo o numerze " << i+1 << " : " << tablica_slow[i] << endl;
}
delete [] tablica_slow;
cin.sync();
}
The problem raises when program reaches the loop, that is supposed to append the letter pointed by the j-index using '.at' method from the string class. I can't find a solution even trying to debug it. Could You help me :)?
You have a typo here
for(j=0;j<=dlugosc_polowy;j=+2)
I assume you meant += instead of =+
for(j=0;j<=dlugosc_polowy;j+=2)
Otherwise you are just assigning 2 to j over and over again.
Your error is reversing two characters:
Change:
`j=+2` to `j+=2`
^^ ^^
(The way it is written j is assigned the value of 2, then, for the rest of its life, stays there.)
for(j=0;j<=dlugosc_polowy;j=+2){
dodane = aktualne_slowo.at(j);
budowane_slowo.append(dodane);
}
replace the j=+2 to j+=2
for(j=0;j<=dlugosc_polowy;j+=2){
dodane = aktualne_slowo.at(j);
budowane_slowo.append(dodane);
}
Related
I'm trying to search with regex to find words like "long tonne" by ignoring any white spaces between "long" and "tonne", which I thought would be best with regex. with the code below, it will print out every converted output but I'm only trying to print one result. ex. if I enter 12 kg, I would only want my result to print the converted to lbs string.
So far, Ive tried :
removing the semi colon after the regex
adding { } brackets before if and after regex
running the code section by section by copying and pasting in another project (which i feel its the regex that I'm having issues with)
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
cout << "Enter your mass with unit: ";
double earthMass;
string unit;
string tolower(unit);
cin >> earthMass >> unit;
regex kg("kg|kgs");
if (regex_match("kg", kg))
{
double dKgToLb;
dKgToLb = (earthMass * 2.20462);
cout << "your converted mass is : " << dKgToLb << " lb" << endl;
}
regex pound("lb|lbs");
if (regex_match("lb", pound))
{
double dLbToKg;
dLbToKg = (earthMass * 0.453592);
cout << "your converted mass is : " << dLbToKg << " kg" << endl;
}
regex longTonne("long\\s*tonne|lg\\s*tn");
if (regex_match("long tonne", longTonne))
{
double dLongToShort;
dLongToShort = (earthMass * 1.12);
cout << "your converted mass is : " << dLongToShort << " sh tn" << endl;
}
regex shortTonne("short\\s*tonne|sh\\s*tn");
if (regex_match("short tonne", shortTonne))
{
double dShortToLong;
dShortToLong = (earthMass * 0.892857);
cout << "your converted mass is : " << dShortToLong << " lg tn" << endl;}
}
else if (!cin.good())
{
cerr << "your input is invalid\n";
return EXIT_FAILURE;
}
}
Here's the code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int keyArray[7] = {1,2,3,4,5,6,7};
int breakPoint;
int counter;
for (counter = 0; counter < 7; counter++)
{
// keyArray[counter] = (rand() % 9) + 1; later
keyArray[counter] = counter; //testing
}
cout << keyArray[0] + "\n";
cout << keyArray[1] + "\n";
cout << keyArray[2] + "\n";
cout << keyArray[3] + "\n";
cout << keyArray[4] + "\n";
cout << keyArray[5] + "\n";
cout << keyArray[6] + "\n";
cin >> breakPoint; //so I can see what the hell is going on before it disappears
return 0;
}
The only reason I gave values to keyArray was that I read in answer to a similar question that you have to initialize an array with data before you use it. But it made no difference. The output is just junk symbols whether you initialize or not.
The compiler is Visual Studio Community 2017. Thanks for any help.
The error is not in your logic but rather in your debugging output. Since the other answers focus on how to fix it, I'll rather explain what happens instead. There seems to be a misunderstanding about the way strings work in C++.
The failure is in this operation:
keyArray[0] + "\n"
Internally, string literals are arrays of characters, in this case const char[2], consisting of the newline and a terminating '\0' null terminator. When you then try to add the integer and this array together, the array will be represented by a pointer to its first element, i.e. it will decay to const char* in order to be used as the second argument to the plus operator used in your code.
So for the compiler, this line will need operator+(int, const char*). But the result of that will be const char*, the input pointer offset by the integer, as that is the operation that happens when adding integers to pointers.
So instead of printing the number and then the string, it will try to access a string that does not exist as the pointer now pointer behind the string "\n" and thus into some arbitrary memory.
Instead of doing
cout << keyArray[0] + "\n"
do:
cout << keyArray[0] << "\n"
or
cout << keyArray[0] << endl
You can't concatanate an integer with a string. That's why you got garbage output
Try this first:
cout << keyArray[0] << "\n";
If you are using compilers that support C++ 11 then try using std::to_string(...) to make a string from an integer before doing the addition:
cout << (std::to_string(keyArray[0]) + "\n");
you cannot concatenate int with string.
change
cout << keyArray[0] + "\n";
cout << keyArray[1] + "\n";
cout << keyArray[2] + "\n";
cout << keyArray[3] + "\n";
cout << keyArray[4] + "\n";
cout << keyArray[5] + "\n";
cout << keyArray[6] + "\n";
to
cout << keyArray[0] << "\n"
<< keyArray[1] << "\n"
<< keyArray[2] << "\n"
<< keyArray[3] << "\n"
<< keyArray[4] << "\n"
<< keyArray[5] << "\n"
<< keyArray[6] << endl;
You need to convert the integers into a string. Using a relatively recent version of C++:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int keyArray[7] = {1,2,3,4,5,6,7};
int breakPoint;
int counter;
for (counter = 0; counter < 7; counter++)
{
// keyArray[counter] = (rand() % 9) + 1; later
keyArray[counter] = counter; //testing
}
cout << std::to_string(keyArray[0]) + "\n";
cout << std::to_string(keyArray[1]) + "\n";
cout << std::to_string(keyArray[2]) + "\n";
cout << std::to_string(keyArray[3]) + "\n";
cout << std::to_string(keyArray[4]) + "\n";
cout << std::to_string(keyArray[5]) + "\n";
cout << std::to_string(keyArray[6]) + "\n";
cin >> breakPoint; //so I can see what the hell is going on before it disappears
return 0;
}
So I recently decided to pick up programming again and went with C++. Tried to make an adventurer class, but I seem to be running into some trouble. Here are my files:
Adventurer.h:
#ifndef __Adventurer_H_INCLUDED__ //if Adventurer.h hasn't been included yet...
#define __Adventurer_H_INCLUDED__ //#define this so the compiler knows it has been included
class Adventurer
{
private:
int hp, mp, str, agi, magic, armour;
public:
Adventurer(){}
void printStats();
}
#endif
Adventurer.cpp:
#include <iostream>
#include "Adventurer.h"
Adventurer::Adventurer()
{
hp = 50;
mp = 25;
str = 5;
agi = 5;
magic = 5;
armour = 5;
}
void Adventurer::printStats()
{
cout << "HP = " << hp << "\n\n";
cout << "MP = " << mp << "\n\n";
cout << "str = " << str << "\n\n";
cout << "agi = " << agi << "\n\n";
cout << "magic = " << magic << "\n\n";
cout << "armour = " << armour << "\n\n";
}
RPG_Game.cpp:
// my first program in C++
#include <iostream>
#include <string>
#include "Adventurer.h"
;using namespace std;
int main()
{
cout << "Hello Adventurer! What is your name? \n";
string advName;
cin >> advName;
cout << "\nYour name is " << advName << "!";
Adventurer *adv = new Adventurer();
cout << adv.printStats();
delete adv;
system(pause);
}
Let's look at the errors in your code
First, in your Adventurer.h, put a semicolon (;) after the class.
Next, in that same class, you have
Adventurer(){}
change this to
Adventurer();
Then, in your RPG_Game.cpp , change
cout << adv.printStats();
to
adv->printStats() ;
When using pointers, you need to use -> and not .
And lastly,
system(pause);
should be
system( "pause" );
Now, try running your code.
Also, you might find this helpful.
I want to print the first 2 values where the next is doubled from the current value.
#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;
bool doubled (int x, int y) { return x*2 == y; }
int main()
{
deque<int> di;
deque<int>::iterator diiter;
for (int i=0; i<=10; i+=2) di.insert(di.end(), i);
for (diiter = di.begin(); diiter != di.end(); ++diiter)
cout << *diiter << " ";
cout << endl;
diiter = adjacent_find(di.begin(), di.end(), doubled);
if (diiter != di.end()) {
cout << "found " << *diiter << " at " << distance(di.begin(), diiter)+1
<< " and " << *(++diiter) << " at " << distance(di.begin(), diiter)+1
<< endl;
}
}
the output is
0 2 4 6 8 10
found 4 at 3 and 4 at 2
not what I expected, which should be:
0 2 4 6 8 10
found 2 at 2 and 4 at 3
What's wrong with my code? I don't understand how the second position is decremented from the first one when I actually incremented it.
Thanks for all help.
Your program is giving strange results because it does not take in to account the fact, that order of evaluation of arguments to a function(In this case operator <<) is Unspecified.
My Answer here, explains the problem in detail & should be a good read.
You need to cout them on separate statements.
cout << "found " << *diiter;
cout << " at " << distance(di.begin(), diiter)+1;
cout << " and " << *(++diiter);
cout << " at " << distance(di.begin(), diiter)+1;
cout << endl;
This works well & outputs the correct/desired output.
I've been trying to format the output to the console for the longest time and nothing is really happening. I've been trying to use as much of iomanip as I can and the ofstream& out functions.
void list::displayByName(ostream& out) const
{
node *current_node = headByName;
// I have these outside the loop so I don't write it every time.
out << "Name\t\t" << "\tLocation" << "\tRating " << "Acre" << endl;
out << "----\t\t" << "\t--------" << "\t------ " << "----" << endl;
while (current_node)
{
out << current_node->item.getName() // Equivalent tabs don't work?
<< current_node->item.getLocation()
<< current_node->item.getAcres()
<< current_node->item.getRating()
<< endl;
current_node = current_node->nextByName;
}
// The equivalent tabs do not work because I am writing names,
// each of different length to the console. That explains why they
// are not all evenly spaced apart.
}
Is their anything that I can use to get it all properly aligned with each other?
The functions that I'm calling are self-explanatory and all of different lengths, so that don't align very well with each other.
I've tried just about everything in iomanip.
Think of it like using Microsoft Excel :)
You think of your stream as fields. So you set the width of the field first then you insert your text in that field. For example:
#include <iostream>
#include <iomanip>
#include <string>
int main()
{
using namespace std;
string firstName = "firstName",
secondName = "SecondName",
n = "Just stupid Text";
size_t fieldWidth = n.size(); // length of longest text
cout << setw(fieldWidth) << left << firstName << endl // left padding
<< setw(fieldWidth) << left << secondName << endl
<< setw(fieldWidth) << left << n << endl;
cout << setw(fieldWidth) << right << firstName << endl // right padding
<< setw(fieldWidth) << right << secondName << endl
<< setw(fieldWidth) << right << n << endl;
}
......
......
The field width means nothing but the width of the text + spaces. You could fill anything other than spaces:
string name = "My first name";
cout << setfill('_') << setw(name.size() + 10) << left << name;
.....
output::
My first name__________
......
I think the best way is to figure out your format then, write a new formatter that does all what you want:
#include <iostream>
#include <iomanip>
#include <string>
std::ostream& field(std::ostream& o)
{
// usually the console is 80-character wide.
// divide the line into four fields.
return o << std::setw(20) << std::right;
}
int main()
{
using namespace std;
string firstName = "firstName",
secondName = "SecondName",
n = "Just stupid Text";
size_t fieldWidth = n.size();
cout << field << firstName << endl
<< field << secondName << endl
<< field << n << endl;
}
If you started thinking about parametrized manipulators, only that accept one int or long parameter are easy to implement, other types are really obscure if you are not familiar with streams in C++.
Boost has a format library that allows you to easily format the ourput like the old C printf() but with type safety of C++.
Remember that the old C printf() allowed you to specify a field width. This space fills the field if the output is undersized (note it does not cope with over-sized fields).
#include <iostream>
#include <iomanip>
#include <boost/format.hpp>
struct X
{ // this structure reverse engineered from
// example provided by 'Mikael Jansson' in order to make this a running example
char* name;
double mean;
int sample_count;
};
int main()
{
X stats[] = {{"Plop",5.6,2}};
// nonsense output, just to exemplify
// stdio version
fprintf(stderr, "at %p/%s: mean value %.3f of %4d samples\n",
stats, stats->name, stats->mean, stats->sample_count);
// iostream
std::cerr << "at " << (void*)stats << "/" << stats->name
<< ": mean value " << std::fixed << std::setprecision(3) << stats->mean
<< " of " << std::setw(4) << std::setfill(' ') << stats->sample_count
<< " samples\n";
// iostream with boost::format
std::cerr << boost::format("at %p/%s: mean value %.3f of %4d samples\n")
% stats % stats->name % stats->mean % stats->sample_count;
}
Give up on the tabs. You should be able to use io manipulators to set the field width, the fill character, and the format flag (to get left or right justification). Use the same values for the headings as you do for the data, and everything should come out nicely.
Also beware that you've switched Rating and Acres in your example.
You can write a procedure that always print the same number of characters to standard output.
Something like:
string StringPadding(string original, size_t charCount)
{
original.resize(charCount, ' ');
return original;
}
And then use like this in your program:
void list::displayByName(ostream& out) const
{
node *current_node = headByName;
out << StringPadding("Name", 30)
<< StringPadding("Location", 10)
<< StringPadding("Rating", 10)
<< StringPadding("Acre", 10) << endl;
out << StringPadding("----", 30)
<< StringPadding("--------", 10)
<< StringPadding("------", 10)
<< StringPadding("----", 10) << endl;
while ( current_node)
{
out << StringPadding(current_node->item.getName(), 30)
<< StringPadding(current_node->item.getLocation(), 10)
<< StringPadding(current_node->item.getRating(), 10)
<< StringPadding(current_node->item.getAcres(), 10)
<< endl;
current_node = current_node->nextByName;
}
}