cpp_is_king
Member
This is the question:
I am getting a segmentation error with this code:
http://pastebin.com/11FmMpSv
hint: words[i+1]
This is the question:
I am getting a segmentation error with this code:
http://pastebin.com/11FmMpSv
hint: words[i+1]
#include <iomanip>
#include <iostream>
#include <ctype.h>
using namespace std;
int isDigit(char ch); //Function 1
int isUpper(char ch); //Function 2
int isLower(char ch); //Function 3
int isAlpha(char ch); //Function 4
int main() //The boss function
{
//Displays a title for the calculator
cout << "\n===============================================================\n" << endl
<< " ~ Welcome to Purple Prose Press Payment Calculator! ~" << endl
<< "\n===============================================================\n" << endl
<< " - Enter characters to calculate.\n" << endl
<< " - Place an ! at the beginning of the line to quit.\n" << endl
<< "---------------------------------------------------------------\n" << endl;
char ch;
//Delcares variables
int numDig, numUpp, numLow, numAlp, totLow, totDig, totUpp, totAlp, totCha;
totDig = totUpp = totAlp = totLow = 0;
ch = cin.get();
while (ch != '!')
{//Starts the first loop
numDig = numUpp = numLow = numAlp = 0;
if (isUpper(ch)) //Refers function 2
numUpp++;
if (isLower(ch)) //Refers function 3
numLow++;
if (isDigit(ch)) //Refers function 1
numDig++;
if (isAlpha(ch))
numAlp++; //Refers function 4
ch = cin.get();
}
//The += will add the individual sets if values and adds them up for the final info display
totDig += numDig;
totUpp += numUpp;
totLow += numLow;
totCha = numDig + numUpp + numLow;
//These cout statements will display the values for the intial lines of characters
cout << " Upper case letters: \t\t\t" << numUpp << endl
<< " Lower case letters: \t\t\t" << numLow << endl
<< " Digits: \t\t\t\t" << numDig << endl
<< " Characters: \t\t\t\t\t" << totCha << endl
<< "\n---------------------------------------------------------------\n" << endl;
ch = cin.get();
} //Ends the first loop
system ("pause")
return 0;
} //Ends the boss function
int isDigit(char ch)
{
if ((int)ch >= 48 && (int)ch <= 57)
return 1;
else
return 0;
}
int isUpper(char ch)
{
if ((int)ch >= 65 && (int)ch <= 90)
return 1;
else
return 0;
}
int isLower(char ch)
{
if ((int)ch >= 97 && (int)ch <= 122)
return 1;
else
return 0;
}
int isAlpha(char ch)
{
if ((int)ch >= 97 && (int)ch <= 27 || int(ch) >= 65 && int(ch) <= 90)
return 1
else
return 0;
}
I need some help with this. I'm absolutely terrible at C++, I hate doing it, and the only reason I've gotten this far with this program is because I've had my friend help me with it. But now I'm in a situation where I can't have that friend help anymore.
All of that is basically just a disclaimer. If I'm missing something stupid, or have done something/everything completely wrong, that's why.
CODE
Anyways, I'm trying to get this to compile. I've gotten it down to two main errors.
EDIT: Fixing the post. The image I uploaded was too big. One sec
ch = cin.get();
}
ch = cin.get();
} //Ends the first loop
} //Ends the boss function
system("pause");
Whoops, while I edited the photo out I also slipped a more recent copy of the code into my post. The most recent one is different from the one you already looked at. My bad.
Thanks a lot for responding though. That's awesome.
#include <iomanip>
#include <iostream>
#include <ctype.h>
using namespace std;
int isDigit(char ch); //Function 1
int isUpper(char ch); //Function 2
int isLower(char ch); //Function 3
int isAlpha(char ch); //Function 4
int main() //The boss function
{
//Displays a title for the calculator
cout << "\n===============================================================\n" << endl
<< " ~ Welcome to Purple Prose Press Payment Calculator! ~" << endl
<< "\n===============================================================\n" << endl
<< " - Enter characters to calculate.\n" << endl
<< " - Place an ! at the beginning of the line to quit.\n" << endl
<< "---------------------------------------------------------------\n" << endl;
char ch;
//Delcares variables
int numDig, numUpp, numLow, numAlp, totLow, totDig, totUpp, totAlp, totCha;
totDig = totUpp = totAlp = totLow = 0;
ch = cin.get();
while (ch != '!')
{//Starts the first loop
numDig = numUpp = numLow = numAlp = 0;
if (isUpper(ch)) //Refers function 2
numUpp++;
if (isLower(ch)) //Refers function 3
numLow++;
if (isDigit(ch)) //Refers function 1
numDig++;
if (isAlpha(ch))
numAlp++; //Refers function 4
ch = cin.get();
//The += will add the individual sets if values and adds them up for the final info display
totDig += numDig;
totUpp += numUpp;
totLow += numLow;
totCha = numDig + numUpp + numLow;
//These cout statements will display the values for the intial lines of characters
cout << " Upper case letters: \t\t\t" << numUpp << endl
<< " Lower case letters: \t\t\t" << numLow << endl
<< " Digits: \t\t\t\t" << numDig << endl
<< " Characters: \t\t\t\t\t" << totCha << endl
<< "\n---------------------------------------------------------------\n" << endl;
ch = cin.get();
} //Ends the first loop
system ("pause")
return 0;
} //ends the main boss function
int isDigit(char ch)
{
if ((int)ch >= 48 && (int)ch <= 57)
return 1;
else
return 0;
}
int isUpper(char ch)
{
if ((int)ch >= 65 && (int)ch <= 90)
return 1;
else
return 0;
}
int isLower(char ch)
{
if ((int)ch >= 97 && (int)ch <= 122)
return 1;
else
return 0;
}
int isAlpha(char ch)
{
if ((int)ch >= 97 && (int)ch <= 27 || int(ch) >= 65 && int(ch) <= 90)
return 1
else
return 0;
}
bool isDigit(char ch)
{
return ( (int)ch >= 48 && (int)ch <= 57 ) ? true : false;
}
So are the errors fixed?
edit: Just realized that the second error would be caused by system("pause") not being called by the main() function because of the first error I described. If you fix the first error and make sure to put system("pause") in the main function it should be fine.
Essentially this is what your code should look like:
Code:
int isAlpha(char ch)
{
if ((int)ch >= 97 && (int)ch <= 27 || (int)ch >= 65 && (int)ch <= 90)
return 1
else
return 0;
}
Code:int isAlpha(char ch) { if ((int)ch >= 97 && (int)ch <= 27 || (int)ch >= 65 && (int)ch <= 90) return 1 else return 0; }
You type casted the parameter wrong. You had it like this: int(ch)
Your code taught me something I didn't know.
I wasn't sure why you saying:
Code:(int) ch
I guess that tells the program to look at the ch character as if it is an integer value?
It's just a type conversion. "ch = cin.get()" is the same thing as doing "cin>>ch". It just reads the input stream and interprets it as a char (since that's the variable you decided to put it in). Using "(int) ch" means that the char will be interpreted as an int. It is actually not really necessary in this example though, since for "ch > 50", ch would already be implicitly converted to an int for the comparison. For example this:Yeah, I think it has to do with the "ch = cin.get()" they had us using for this. It has it's own set of rules that comes with it.
char ch = 'A' + 1
Code:int isAlpha(char ch) { if ((int)ch >= 97 && (int)ch <= 27 || (int)ch >= 65 && (int)ch <= 90) return 1 else return 0; }
You type casted the parameter wrong. You had it like this: int(ch)
My professor, I guess. She hasn't mentioned the bools at all. Is that an easier way of doing things?
Josh:Smitha:05-12-1982:junior:100-10-1000:c
C++ is more than capable of what you want to do. Have you got any experience at all in programming with C++? Anyway, I'll list some useful tips and see if you can figure it out yourself.This question pertains to either Windows Server or Fedora
I don't know if this would be the best place to ask, but I too need help with coding, however, I'm not sure if what I'm trying to write can be wrote with C++ or not; I assume it can be though. Basically, my teacher is having us write a program that takes a text file that already has information in it, and once it's prompted through cmd, the program then is supposed to add users to the computer based on the information in the text file. The text file has 100 lines containing text that looks similar to this (without the " on either side.) for each unique user:
We are required to have three different groups: students, faculty, and staff. Each user is supposed to be added to said specific group depending on if their listed as a teacher, staff, or freshman, sophomore, junior, and/or senior. We need to have the username formatted to be the first letter of the first name and the whole last name, including the last 2 digits of the social at the end (ex. jsmitha00). The password is just the users 8 digit birthday.
So to be short, I basically need the program to format all the accounts with the style the previous example has, create passwords using the birthday, and be put into the specific groups. Also, at the end of the first account I provided there is a letter c, only the accounts with the letter c are to be added, but the ones with a letter q are not to be added.
Unfortunately this isn't a coding class and I don't know anything about coding, so I haven't even figured out where to start!... Shit, I don't even know if C++ is what I'm supposed to be using! I'm going to ask my teacher for help tomorrow but I don't see him actually telling me much, so I figured I'd ask my fellow gaffers for a bit of input beforehand. If what I said doesn't make sense please let me know and I'll try to explain it better. I just need whatever help someones willing to provide, this assignment is confusing the hell out of me.
int main(int argc, char* argv[]){
}
ifstream in("test.txt");
in.close();
in.open("test2.txt");
in.close();
if(!in){
//the file couldn't be opened, handle the error
}
string line;
while(getline(in, line)){
stringstream stream(line);
string word;
while(getline(stream, word, ":"){
}
}
What do people think about boost::lexical_cast and its use of exceptions to communicate failure? I pretty much never use exceptions, but I'm doing some text parsing and I'm suddenly seeing why they might be useful. Propagating errors up to where they need to be handled is driving me nuts, especially because there are a million and one ways in which a string may be invalid.
class Parser {
virtual bool tryToDecode(const QString& string, Coordinate& output) = 0;
};
class Parser {
virtual Coordinate decode(const QString& string) = 0;
};
I was just trying to use boost::lexical_cast as an example, really. I'm wondering if exceptions might help me simplify my interface, or if I'll face any significant performance penalties for their use.
I'm trying to parse coordinates and there are a few coordinate formats that I want to try before I decide the user has given me garbage. My interface now is looking something along the lines of:
Code:class Parser { virtual bool tryToDecode(const QString& string, Coordinate& output) = 0; };
I plan to have a few parsers to handle different types of coordinates, but I think this is a little ugly. I was thinking I might be able to do better if I used exceptions and simplified the interface.
Code:class Parser { virtual Coordinate decode(const QString& string) = 0; };
Then I could easily communicate failure easily from within my parsers, have a simpler interface, and perhaps include an error message that actually explains why it failed (useful for testing and debugging).
Given that I've never used exceptions before, I'm wondering if that's a reasonable use of them for improving my code. Or, alternatively, if you have other suggestions. My current interface works (I've completed the first parser), but could be better.
struct Parser
{
virtual bool TryParse(const QString& string, Coordinate& output) = 0;
virtual void Parse(const QString& string, Coordinate& output)
{
//return void instead of Coordinate as a micro-optimization, if that matters to you
if (!TryParse(string, output))
throw new exception("Invalid number format.");
}
};
bool success = false;
Coordinate c;
for (auto it = parsers.begin(); it != parsers.end() && !success; ++it)
success = it->TryParse(string, c);
bool success = false;
Coordinate c;
success = success || ParseStrategy1(string, c);
success = success || ParseStrategy2(string, c);
success = success || ParseStrategy3(string, c);
success = success || ParseStrategy4(string, c);
DoSomething(input, output, ParseStrategy2);
template<class A>
void Parse(const string& string, A& output)
{
if (!TryParse(string, output))
throw exception("Error parsing input");
}
Coordinate decode(const QString& string)
void Parse(const QString& string, Coordinate& output)
Two pieces worth reading, first the classic wtf exceptions essay from yore:
http://ptgmedia.pearsoncmg.com/images/020163371x/supplements/Exception_Handling_Article.html
The canonical rebuttal:
http://www.boost.org/community/exception_safety.html
That said, it depends largely on the precedent of the environment in which you're programming since something like exception handling is generally a global framework state--it's either required or forbidden, usually the latter.
cpp_is_king sounds like he's going through the 12 stages of c++ grief. He'll be iso_c99_is_king before you know it .
I haven't really seen any good arguments for avoiding exceptions in C++, but I'm also no expert and I realize C++ is kind of its own beast.
Coming from the .NET world, coding without exceptions seems like madness to me. Returning error codes is like, a huge violation of coding style and convention. The exception safety article on the boost site linked above makes 100% sense to me.
I also agree that you should go with whatever is standard in your code base. If this is a project only you will be working on, go with whichever you prefer. Personally, this version makes much more sense to me:Code:Coordinate decode(const QString& string)
I have no idea why anybody would use this:Why return void and take an output parameter? That seems insane to me. Again, I recognize this isn't really my domain. Not asserting I'm right or anything.Code:void Parse(const QString& string, Coordinate& output)
If he's programming in C#, the return type is a pointer and it is harmless to return that. Probably where a lot of the confusion comes from.
In C++ you need to use non-const reference parameters all the time. No way would you want to ever return a container class by value.
I tend not have have that problem because Qt's containers are implicitly shared. They're all copy-on-write. Both output variables and exceptions are things I rarely deal with due to the libraries I use.
How in the world are you in a class that asks you to do that if you have no prior programming experience? Surely it would have been a prerequisite?
I mean, don't panic, it's manageable. I'm just curious.
Sorry, I didn't mean to imply anything with that. I just wanted to expand a bit on what you said.
STL is certainly a different style entirely. It's almost strange how two programs can both be C++ and do things completely differently. There's a few different C++ 'worlds'.
Yeah, you can certainly have a very very wide range of perfectly legitimate styles in C++. I've been slowly moving my style over to using far more non-member functions in namespace (global and anonymous). I started moving this direction after reading: http://drdobbs.com/184401197
Previously, I would have almost all of my functionality in classes. However, slow began moving as many functions as I could to namespaces. For private functions, I've tried to make them anonymous functions in the cpp. A change to the signature of these functions no longer requires a recompilation of all the files that include the header.
Function that must access private member variables are not the ones Meyers is referring to. He's only talking about functions that could be equally implemented as non-freiend, non-member functions (ie: don't depend on private implementation).That's definitely useful, especially for large projects, but how do you deal with accessing private member variables?
There are different degrees of broken code. Changing the name of a function from ApplyForce() to ApplyForces() has a far less severe impact as changing the way users interact with your class entirely. Additionally, the way he seems to define a "corresponding change" between his two examples seems flawed as well.This leads to a reasonable approach to evaluating the relative encapsulations of two implementations: if changing one might lead to more broken code than would the corresponding change to the other, the former is less encapsulated than the latter.
I don't get this either. If a function could just as easily be moved to a non-member, non-friend function, then it's also a function that would NOT be broken when your class's private implementation changes. And if it would be broken, it would be just as broken as some global or namespaced function as it would in your class. Encapsulation as a whole would not be decreased, only the encapsulation that could be blamed on your class directly.We've now seen that a reasonable way to gauge the amount of encapsulation in a class is to count the number of functions that might be broken if the class's implementation changes. That being the case, it becomes clear that a class with n member functions is more encapsulated than a class with n+1 member functions.
Function that must access private member variables are not the ones Meyers is referring to. He's only talking about functions that could be equally implemented as non-freiend, non-member functions (ie: don't depend on private implementation).
I don't completely buy all his points. Mostly because his definition of Degrees of Encapsulation is wrong to me.
There are different degrees of broken code. Changing the name of a function from ApplyForce() to ApplyForces() has a far less severe impact as changing the way users interact with your class entirely.
Additionally, the way he seems to define a "corresponding change" between his two examples seems flawed as well.
I don't get this either. If a function could just as easily be moved to a non-member, non-friend function, then it's also a function that would NOT be broken when your class's private implementation changes. And if it would be broken, it would be just as broken as some global or namespaced function as it would in your class. Encapsulation as a whole would not be decreased, only the encapsulation that could be blamed on your class directly.
//foo.h
class Foo
{
public:
enum {IMPL_SIZE = 32};
Foo();
void PublicInterfaceMethod1();
void PublicInterfaceMethod2();
void PublicInterfaceMethod3();
private:
uint64_t mImpl[IMPL_SIZE / sizeof(uint64_t)];
};
//foo.cpp
class FooImpl
{
uint64_t mMember1;
uint64_t mMember2;
uint64_t mMember3;
uint64_t mMember4;
};
Foo::Foo()
{
static_assert(sizeof(FooImpl) == sizeof(Foo::mImpl));
new(mImpl) FooImpl();
}
void Foo::PublicInterfaceMethod1()
{
((FooImpl*)mImpl)->PublicInterfaceMethod1();
}
void Foo::PublicInterfaceMethod2()
{
((FooImpl*)mImpl)->PublicInterfaceMethod2();
}
void Foo::PublicInterfaceMethod3()
{
((FooImpl*)mImpl)->PublicInterfaceMethod3();
}
What background do you have? For most technical fields it's probably a good idea to know some programming these days. Anyway, a program that does what you want would be quite simple, you would probably be able to do it without much problem after taking any sort of introductory programming course.Thanks for the info guys, but luckily my teacher said he'd find some other project for me to do. I was stressing that damn assignment like no other.
And Rez, the class is Applied Centric Computing or basically learning about servers, domains, and other things of that manner. They are prerequisites to the class, but none that involve learning how to code. Maybe because it's a 4000 level computer course he assumed that most of us had coding experience or something? Hell I'm not really sure, I can't complain though because most teachers aren't as forgiving as he is and would have made me do the assignment like everyone else.
That's not to say that I wouldn't mind learning some programming though. I was just led to believe that most companies had their programs created by software developers either in or out of the company, but seems like it'd be best for me to learn some programming for cases like this. Would that program I asked about be considered pretty simple? It doesn't seem like it'd be too hard to create if I just knew a language.
I always thought that the pimpl idiom takes things a bit far. Its a compensation for poor languages decisions.Since we're talking about basically the pros and cons of the pimpl idiom, I might as well mention as an aside that there's an interesting way to implement the pimpl idiom in a way that avoids their biggest problem: the dynamic pointer indirection. Of course, nothing in life is free, the tradeoff should be immediately apparent.
I always thought that the pimpl idiom takes things a bit far. Its a compensation for poor languages decisions.
typedef float32x2_t vec2_t;
typedef float32x3_t vec3_t;
typedef struct _vertex_t {
vec3_t pos;
vec2_t uv;
vec3_t normal;
uint32_t color;
} vertex_t;
typedef void* mesh_t;
mesh_t mesh_alloc( void );
void mesh_init( mesh_t mesh );
void mesh_fini( mesh_t mesh );
void mesh_free( mesh_t mesh );
size_t mesh_num_verts( mesh_t mesh );
const vertex_t* mesh_get_verts( mesh_t mesh );
/* etc. */
Indeed. In ISO C99 land our version of this is opaque interfaces for anything but the simplest of POD types:
Code:typedef float32x2_t vec2_t; typedef float32x3_t vec3_t; typedef struct _vertex_t { vec3_t pos; vec2_t uv; vec3_t normal; uint32_t color; } vertex_t; typedef void* mesh_t; mesh_t mesh_alloc( void ); void mesh_init( mesh_t mesh ); void mesh_fini( mesh_t mesh ); void mesh_free( mesh_t mesh ); size_t mesh_num_verts( mesh_t mesh ); const vertex_t* mesh_get_verts( mesh_t mesh ); /* etc. */
Although this is a contrived example (in game code we rarely care about this since we're focused on performance and delivering a specific game, not some abstract engine or library), it gets the idea across.
Yeah, you can certainly have a very very wide range of perfectly legitimate styles in C++. I've been slowly moving my style over to using far more non-member functions in namespace (global and anonymous). I started moving this direction after reading: http://drdobbs.com/184401197
Isn't there a pretty basic logical error in his justification of why the non-member function would be better?
If the function could be implemented as a member function that only accesses the public interfaces, then it would not break if private data were changed (provided the programmer actually uses only the public interfaces). In that case it would have neutral effect on the level of encapsulation.
You might say that there is no purpose to include it in the class if it uses only the public interfaces, but it might still be included in the class for the purpose of code organization or maintaining the Object paradigm.
// Pre: is_permutation(v)
// Post: Returns the number of reversals needed to make v[0] == 1
// if the reversal game were played on v.
// Note: If ``v[0] == 1`` initially, then ``score(v)`` returns 0.
int score(const vector<int>& v) {
assert(is_permutation(v));
int score = 0;
vector<int> v_test = v;
while(v_test[0] != 1) {
if(v_test[0] == v_test.size()) {
reverse(v_test.begin(), v_test.end());
++score;
}
else {
reverse(v_test.begin(), v_test.begin()+v[0]);
++score;
}
}
return score;
}