I would recommend using a color picker control rather than a combobox, if only for the compactness of the design.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
In this case, the error is most likely in one of the header files you are including, with the most probably cause being that you omitted a semi-colon at the end of a class definition.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Take a look at Head First Java, if you have the opportunity to do so before buying it. It seems to be a book people either love or hate; The style of is offputting to many, but those who can get into it without being overly distracted often find it to be excellent. Thus, I don't recommend buying it sight unseen, but if you can check it out of a public library or read a preview version online, do so.
Mind you, I don't really recommend Java as a first language in the first place; While it is not as difficult to master as C++, it still involves a lot of boilerplate code that gets in the way of learning, IMAO. Python or Ruby would be better choices, for most newcomers; I personally favor Scheme, especially the classic Structure and Interpretation of Computer Programs (which, among other things, is available online for free, and can take you through a whole CS curriculum in 6 chapters), but that's very much a minority opinion these days - it is another 'love it or hate it' sort of book.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Branickiod: I think you are confused. This is the C++ foru, not the SQL Server forum, and the text you quoted isn't relevant to the matter at hand in any way, shape or form. I know you meant well, but please pay more attention to where you are posting in the future.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Oh, sorry; I should have provided more information. The Java HashMap
generic class is a standard Collection
that behaves as a dictionary or lookup table (sometimes also called an associative array or associative map). It provides a mapping between two values.
When you create the HashMap
, you give it two types, one for the key and the other for the value. You add key-value pairs to the HashMap
to make the table. You can then use a key to look up a value in the HashMap
.
As for why they are superior to an ArrayList
, they aren't; they are used in a completely different way from an ArrayList
with very little overlap. What they are superior to in this case is the long sequence of if()
statements which you were using to determine the values for the cards. Not only is it more compact, you can use it in mutiple locations with very little code. It is an approach known as data-directed programming, where you use the structure of the objects to provide the solution to a problem rather than relying on code for it.
Oh, I noticed a few errors in my earlier code; notably, I used ==
where I should have used .equals()
, and forgot to pass card
to the .get()
method of the HashMap
.
if (card.equals("Ace")) {
if (dValue <= 10) {
dValue += 11;
}
else {
dValue += 1;
}
}
else {
dValue += faceValues.get(card);
}
HTH.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
The simple answer for why b
is not defined in this loop:
while b <= 10:
print (b)
b += 1
is that b
is not, in fact, defined, at least not when you are trying to compare it to 10. Thus, you do indeed want to initialize it to zero before the beginning of the loop.
But wait, you say, why then is it causing an infinite loop, when you clearly have an increment in the loop? Well, the answer there is, you don't have an increment in the loop; you have an increment after the loop, where it does you no good at all. This is simply a matter of incorrect indentation, and easily is solved thusly:
b = 0
while b <= 10:
print (b)
b += 1
To finish up, let me answer a question which you haven't asked: why doesn't the while:
loop's conditional value default to zero, when the equivalent for:
loop's is:
for b in range(0, 11):
print (b)
The answer is that the value of this b
is getting set by the range()
generator on the first pass of the loop, and is reset on each subsequent pass.
Lucaci Andrew commented: Nicely done +4
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
On the card values, I would recommend using a HashMap
as a reverse lookup table for the card face values. Something like this should do:
private HashMap<String, int> faceValues = new HashMap<String, int>(20);
faceValues.put("Ace", 1);
faceValues.put.("Deuce", 2);
faceValues.put("Trey", 3);
// handle all the numbered cards
for (int i = 4; i <= 10; i++) {
faceValues.put(Int.toString(i), i);
}
faceValues.put("Jack", 10);
faceValues.put("Queen", 10);
faceValues.put(King", 10);
You'll need some additional logic for handling the case where Ace is treated as 11, but beyond that, this should make looking up the card values much easier.
/*
* Dealers Cards Value
*/
public int getDealersValue(int dValue) {
dValue = 0;
for(int i = 0; i < dealersCards.size(); i++) {
String card = dealersCards.get(i);
if (card == "Ace") {
if (dValue <= 10) {
dValue += 11;
}
else {
dValue += 1;
}
}
else {
dValue += faceValues.get();
}
}
dealersValue = dValue;
return dValue;
}
The same would be done with the user's cards, except that the user would have to be queried abuot how to treat the aces.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
And what seems to be the trouble with it? I can see that it is incomplete, but you will need to spell out just what you need help with.
Seriously, PoloBlue, you have been posting here long enough that you should know better than this by now. We are not mind readers; while we'll help you to the best of our abilities, we can't simply guess at the problems and hope to be right.
I can point out a few things, but that's about it. First off, you haven't actually implmented the main loop yet. The program runs through the sequence once, and stops, with no final message.
Second, the GetCustomerInfo()
function returns a string, but you don't actually assign that string to a variable anywhere in main()
; the customer information is simply getting lost. The same is true for MonthlyInterestRateCalculator()
and MonthlyPmtCalculator()
.
Now, I don't know if you've covered structures in your class yet, but you might find it useful to declare the following struct types:
struct Customer
{
string firstName, lastName;
};
struct LoanInformation
{
double loanAmount;
double annualIntRate;
int No_of_Months;
};
This helps organize the data and makes it easier to pass the data around between the functions.
As for the header issue, I've already said my piece about that, and see little point in re-hashing the issue with you; but as I said before, if you need help in setting up a project file to work with multiple compilation units, let me …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
There is another approach to this, which would not require you to rebuild the list; however, the technique needed is not that different from that used to reverse the list, so which would be the most useful would depend on the overall goal. In essence, what you would do is recurse down the length of the list, then apply the operation you need to perform on the list:
struct Node
{
int data;
struct Node* next;
};
void printReverse(struct Node* list)
{
if (list == NULL)
return;
else
{
printReverse(list->next);
printf("%d ", data);
}
}
This is jut a quick-and-dirty example; you'd need to apply the technique as appropriate.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Well, first off, regarding the libraries you've included, I would recommend using the C++ versions rather than the C-style names. All standard C++ headers now omit the '.h' extension, and for the older C headers, prepend them with the letter 'c'. Thus, <stdlib.h>
should now be <cstdlib>
, <string.h>
should be <cstring>
and so forth. This change was made over a decade ago, and I am surprised that the Visual C++ compiler doesn't give a warning about that.
On a related note, the <conio.h>
header is a proprietary one, and deprecated. It was specific to the oldr DOS console, and while the Windows console is similar, there are significant differences. Since the only place you actually used anything in it is commented out, I would recommend removing it completely.
Is there a particular reason you are using the C-style file I/O instead of the C++ iostreams? The C++ style file I/O is generally a lot easier to use. In this case I doubt it would make much of a difference, but it is worth asking about.
I notice that you close the file and then open it again immediately afterwards. This appears to be used mainly to reset the file position back to the start of the file. This shouldn't be necessary, as you can avoid a lot of overhead by using the following line of code instead:
fseek(f_init, 0, SEEK_SET);
Since you use fseek()
earlier, I am surprised that you didn't do it this way.
Finally, I tested …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
There really aren't any specific rules about making wrapper casses I'm afraid; it depends too much on the functions and structures which are being encapsulated. Some wrapper classes are nothing more than a static class with a group of methods that call the original functions directly being nothing more than a way of organizing the existing functions into a single package. Others focus on building a class around a data structure, with the aim of simplifying the function calls by making them methods of the data structure, rather than having to apply the functions to the data. Still others may actually combine behaviors in ways that actually change the way the library works, though at that point you generally wouldn't call it just a wrapper.
The closest thing to a general method or approach which I've found was this article, and I'm not sure it really applies generally. TheAdapter Pattern is often seen as a type of wrapper, but it isn't necessarily done as a wrapper class per se, IIUC.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Before we get to the specific issue, I'd like to mention a few things. First, it is incorrect to use void
as the return type of the main()
function; according to the C++ language standard, you should always use int main()
. Some compilers do allow void main()
, but strictly speaking it is incorrect.
Second, you are using the older form of the header files. In modern C++ (since the 1998 standard), the correct standard library headers no longer use the '.h' extension; thus, it should be <iostream>
rather than <iostream.h>
. On a related note, the C++98 standard also requires that all standard library classes, tyoes, and objects be placed in the std
namespace. Thus, you would need to scope the references to std::cout
and std::cin
.
(BTW, what version of the compiler are you using? If it is the Turbo C++ compiler, you should be aware that that is over twenty years old, and you ought to replace it with something newer. There are several good free compilers available that support the latest version of the standard, so there's no reason to use the older compiler if you have any choice in the matter.)
Finally, you should be aware that the <conio.h>
library is proprietary to the Borland compilers, and is specific to DOS programs (which is not the same as Windows console, though the console is backwards-compatible with DOS to a degree). It is both non-portable and outdated, and you are best off avoiding it.
Now we get to the …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
What have you tried so far? Show us your code - or just some pseudo-code - and we'll help you debug it.
If you aren't sure where to start, start by figuring out how you are going to read in a given line of text and parse it. I recommend using the getline()
method of your input stream, saving the line into a string, and then breaking it up into pieces using a stringstream
. This would make processing the file line by line much easier.
Are the $Elements
and $EndElements
tags part of the actual file format? If so, I would start by scanning for $Elements
, after which you would loop on each line, testing to see if you have found $EndElements
.
If it is allowable, I would recommend using a vector
of vector
s of double
to hold the data:
vector< vector<double> > table;
I suspect, however that this would not be allowable under the rules of the project, which presumably is to teach you how to write data structures for handling unevenly sized data on your own. If that's the case, you'll want to write a linked list class, with each link representing a row, and the data columns inside the list nodes as a dynamically allocated array of double
.
class TableRow
{
private:
unsigned int row_number;
size_t row_size;
double* columns;
TableRow* next;
public:
TableRow(unsigned int row, size_t size) : row(row_number), size(row_size)
{
next = 0; // initialize next to null
columns = new double[row_size];
} …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Programmatically, you mean? What is your intention with it? If this is a one-time deal, you might be better off just using the hex editor.
Also, what compiler are you using, and does it have any sort of library available for this purpose? Do you you intend to manipulate the file directly? Does the program need to display the bitmap in any way while you ae working on it?
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
In this context, the ampersand is the reference type indicator; it means that instead of passing the value of the arguments, it should pass a reference to them. A reference is similar to a pointer, in that it let's you act on the original variable rather than a copy.
In practical terms, this means that when you change the values of b
and e
in the function bande()
, it also changes the values of the b
and e
in the main()
function.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Ah, I went and made a copy of the project into Visual C++ Express 2010, and when I compiled it there, I got exactly the same errors you mentioned (which also answers my question about what compiler you used). Checking into things a bit, I found that the variable intResult
was actually declared as type double
for some reason, which was the cause of the warning - implicitly converting a double
to an int
does indeed lose information in most cases.
The easiest solution is to change the variable declaration. However, since it looks as if the declaration is part of the code given to you by the instructor, I don't know if the project rules allow you to alter it or not. Assuming you can, then you get another such warning on the line
intResult = divide(number1, number2);
... as divide()
returns a double
. This can be fixed by explicitly converting the double
to an int
using the floor()
function
intResult = floor(divide(number1, number2));
It still loses information, but now at least it does so explicitly. And now at least the variable name intResult
makes sense...
This leaves the last warning, which basically says that you declared doubleResult
but never used it. To get rid of the error message, you can just comment the declaration out.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
All kidding aside (wait, who was kidding?), I was able (after moving the code out of the header and into a separate compilation unit.... grrrr) to compile and run this without getting those warnings. I did get a confilct with a part of the STL, but fixed that by renaming minus()
to subtract()
, after which it compiled cleanly. Why your compiler is catching this and mine isn't doesn't seem clear.
BTW, which compiler and IDE are you using? I may be able to explain how to use the project files so you can link multiple compilation units, if I knew which one you were using.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Again with putting code in the header files... sigh. Worse, it is now clear that this horrible practice is being perpetrated and perpetuated by your instructor, who apparently wrote the majority of said code in this fashion, leaving only sections for you to fill out.
<rant>
Either your professor is too lazy to explain how to use project files (or Makefiles), or too incompetent to teach them. Given the excrable quality of the code provided, I am inclined towards the latter. Either way, this course is doing you a disservice, and you'd be better off learning on your own than continuing with this idiot of a professor.
</rant>
Sorry, now that I've got that off my chest... nothing to see, move along.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
The problem is that you are trying to use files
as a filename, when it is a list of filenames (well, technically file paths, but anyway). You need to either index the specific one of the list elements you want, or else iterate through the list of filenames.
import glob
from lxml import etree
from subprocess import call
files=glob.glob('mypathname/LS*/*.xml')
files.sort()
for (count, aFileName) in enumerate(files):
F=open(aFileName, 'r').readlines()
nf=[]
for line in F:
nf += line.replace('.2','')
new=open('test{0}.cpp'.format(count), 'w')
for line in nf:
new.write(line)
new.close()
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Uhm... just what did you want to know, or needed help with?
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
That depends, I would say, on how you mean to use the two methods. Personally, I would probably have only one form of the method, one which takes an istream&
as it's argument; this covers both the case of a file input (ifstream&
) and string input (istringstream&
), and gives you additional options besides (e.g., reading from std::cin
for a filter).
I would add that you may want to have it return a vector
of an abstract Token
class, rather than of plain std::string
s. This would allow you to specialize the set of tokens a given Lexical
object returns with additional information aside from the contents of the string itself.
Or perhaps you could combine the two sets of ideas, and have it return a stream of Token
s? You'd need to define a tokenstream
class, as an extended form of an ios
, and then... hmmn, let me think this out a bit.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
With a bit of extra work, I think you'll find this solves (most) of the issues with your code:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
int precedence(char c)
{
switch(c)
{
case '*':
case '/':
return(2);
case '+':
case '-':
return(0);
}
}
void to_postfix(char *infix, char* postfix)
{
char stack[30];
int i=0,j=0,top=-1;
while(infix[i] != '\0')
{
if(isalpha(infix[i]) || isdigit(infix[i]))
{
postfix[j++] = infix[i++];
}
else if(infix[i] == '(')
{
stack[++top] = infix[i++];
}
else if(infix[i] == ')')
{
while(stack[top] != '(')
{
postfix[j++] = stack[top--];
}
top--;
i++;
}
else
{
while(top != -1 && stack[top] != '(' && precedence(infix[i]) < precedence(stack[top]))
{
postfix[j++] = stack[top--];
}
stack[++top] = infix[i++];
}
}
while(top>-1)
{
postfix[j++] = stack[top--];
}
postfix[j] = '\0';
}
int main()
{
char infix[30], postfix[30];
fgets(infix, 30, stdin);
to_postfix(infix, postfix);
puts(postfix);
return 0;
}
HTH.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
First off, stop using the SMS abbreviations; no one will take you seriously here if you insist on that sort of thing. Write out clear, complete English sentences, to the best of your ability, please.
Second, while I know it is a picayune point to make, void main()
is not valid in a portable C program; the older standard allowed it, but the only really correct form is int main()
.
On a related note, drop the #include <conio.h>
directive - <conio.h>
is not a standard header, and you don't use any functions from it in any case.
Finally, never, ever use gets()
- it is too dangerous, because it is unbounded and can overrun the buffer you are reading the data into. Please use fgets()
in the future.
That having been said: what is the program actually doing, and how is it failing? As it is right now, my C compiler gives three warnings when I compiler the code:
Compiling: C:\Users\Jay\Documents\Programming\postfix.c
C:\Users\Jay\Documents\Programming\postfix.c: In function 'to_postfix':
C:\Users\Jay\Documents\Programming\postfix.c:22:19: warning: comparison between pointer and integer [enabled by default]
C:\Users\Jay\Documents\Programming\postfix.c:54:15: warning: assignment makes integer from pointer without a cast [enabled by default]
C:\Users\Jay\Documents\Programming\postfix.c:55:5: warning: function returns address of local variable [enabled by default]
Linking console executable: C:\Users\Jay\Documents\Programming\postfix.exe
Process terminated with status 0 (0 minutes, 0 seconds)
0 errors, 3 warnings
The last one I suspect is the critical one - you are passing the back the value of postfix
, but postfix
is a local variable of to_postfix()
, which means it won't have …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Actually, let's start over with new variable names, just to make it clearer, and add some test prints to show what is happening at each stage. I did this and was able to get the program working, in fact:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int iterations, initial_tax_years, increased_tax_years, product_tax, total_years;
int i, j, k;
long int* total_tax;
long int *annual_tax;
printf("How many iterations to test: ");
scanf("%d",&iterations);
total_tax = (long int) calloc(iterations, sizeof(long int));
for(i = 0; i < iterations; i++)
{
printf("How many years for the first tax increase period: ");
scanf("%d",&initial_tax_years);
printf("How many years for the second tax increase period: ");
scanf("%d",&increased_tax_years);
printf("How many years for the final tax increase period: ");
scanf("%d",&product_tax);
printf("How many total years to review: ");
scanf("%d",&total_years);
annual_tax = (long int*)calloc(total_years, sizeof(long int));
printf("How much was the initial tax payment: ");
scanf("%ld", &annual_tax[0]);
/* print out the initial state */
printf("\n\nyear 0 == %d\n", annual_tax[0]);
for(j = 1; j <= initial_tax_years; j++)
{
annual_tax[j] = annual_tax[j - 1] + 1;
printf("year %d == %d\n", j, annual_tax[j]);
}
annual_tax[j] = annual_tax[j - 1] + 1;
for(j = initial_tax_years + 1; j <= (initial_tax_years + increased_tax_years); j++)
{
annual_tax[j] = annual_tax[j - 1] * 2;
printf("year %d == %d\n", j, annual_tax[j]);
}
for(j = (initial_tax_years + increased_tax_years + 1); j < total_years; j++)
{
annual_tax[j] = 1;
for(k = 1; k <= product_tax; k++)
{
annual_tax[j] = annual_tax[j] * (annual_tax[j - k]);
}
printf("year %d == %d\n", j, annual_tax[j]);
}
total_tax[i] = annual_tax[total_years - 1] …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
To post a code sample, you can use the Code button on the editing bar just above the editing pane. This should open up a new window where you can paste the code samples. Alternately, you can simply indent the line four spaces, with extra lines between the code and the text.
For more details, go to the link where it says Markdown Syntax: Formatting help, above the editing pane on the right hand side.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Oh, and the OP cross-posted to DevShed. Just so everyone is aware of it. BTW, if I can find this as easily as I did, don't you think that the professor will find it here, too? It has happened before, so it isn't as implausible as it sounds, and I can assure you that schools don't take kindly to this sort of thing.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
I would recommend starting off with the representation of the deck of cards. Have you studied classes and object-oriented programming yet? If you have, then the easy thing to do is create a class Card, which can have one of the 52 face and suit values, then use that to create a Deck class. You can even subclass Deck to make a Hand class (or at least, that was how I did it when I was writing my old Acey-Deucy simulation - it's just too bad that I don't have a copy of it on hand for you :p I think I may have posted it somewhere, though, so hint hint perhaps a search would help...).
Once you have a simulation of the card decks, you can simply write the game by applying the scoring rules to each hand.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
I think I see the problem here; you are making an understandable but incorrect assumption about how arrays work in C. In C, arrays do not start with the element one, but rather with element zero. Conversely, the last element of an array is not the size of the array, but the size of the array minus one. To put it another way, the elements of an array declared int a[4];
would be a[0]
, a[1]
, a[2]
, and a[3]
. There is no a[4]
in a four-element array in C; the 4 in the declaration is the size of the array, not the index of the last element.
Thus, the correct way to walk through an array is
int i;
int a[10];
for(i = 0; i < 10; i++)
{
// do something here
}
There are good, if somewhat obscure, technical and mathematical reasons for zero-indexed arrays; this blog article covers one line of reasoning on the subject, and the Wikipedia article on Zero-Based Numbering gives an overview of a few more. Suffice it to say that, except for a few older languages, almost all programming languages use zero-indexed arrays, for better or for worse.
As for the compiler, you might find Visual C++ Express easier to use than CFree, I'm not sure. However, since CFree will work with the newest version of MinGW, the easier solution is to download and install MinGW, then set CFree to use the newer version …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
OK, I just looked into CFree a bit, and found out that the default compiler for CFree Standard 4.0 is GCC for MinGW, version 2.95, a version which dates from around 2002 if I am not mistaken. That's a whole lot better than what I was worried about (ten years newer and after the C99 and C++98 standards), but still quite old.
Since CFree is a general-purpose C/C++ Integrated Development Environment that is not specific to any given compiler, you should be able to install and use a newer version of the MinGW port of GCC without any trouble, which would get you (almost) up to date with the latest version of GCC.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Not little changes, no; enormous ones. The entire C++ language was overhauled in the 1998 ISO standard, and again last year in the 2011 ISO revised standard. The big change in the 1998 version was the introduction of namespaces, which was what prompted the changes in the standard headers (the old headers were, for a while, allowed for the sake of backwards compatibility in older code that didn't use the namespace system, but have been phased out since then).
This is just in the standard C++ language itself. Visual C++ has a whole raftload of proprietary additions to C++, as well, and if your professor teaches those, well, they are worh knowing about, but you ought to understand that they aren't really part of the language as it is used by the rest of the world.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
To address the last question first, it depends on which compiler you're using, and wether it is configured to catch all of these given issues. I have my compiler set to warn me about a lot of things which aren't, strictly speaking, errors in C, but which are nonetheless causes of bugs. Even with that, however, it didn't catch the problem with not having n
initialized; I noticed it myself, when going through the code. As for the header issue, what it actually warned me of was that calloc()
was not declared before use, and that the return value did not match the default; it took a bit of experience and familiarity with the standard library to recognize the cause of the problem.
Speaking of compiler differences: when I compile and run the code as given, I get a segfault. I tracked this down to the last of the for()
loops, where you have the conditionals in the form
for(l = (s1+s2); l<=n; l++)
{
ptr[l]=1;
for(m=1; m < k; m++)
ptr[l]=ptr[l]*(ptr[l-m]);
}
The problem is that l
(a very bad variable name, BTW - it can too easily be confused with 1
when reading the code) is being tested as less than or equal to n, which means that on the last loop, l
equals n
. This is a problem, because the indices of the array only go from 0 to n - 1. Thus, you are walking off the end of the array during the …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
First off, I would say that this is different enough that you would have been better off creating a new thread, rather than posting in one several months old. Just for future reference.
While I cannot say for certain without seeing the code, from the error message given it sounds like the issue is namespace scoping. You see, the majority of objects and classes in the standard library are in the std
namespace, and have to be scoped for it in order for them to be visible, even if you have the headers which hold them #include
d already . To do this, you have three options:
- You can explicitly scope each reference to the object by prepending them with the
std::
scope marker; e.g.,std::cout
,std::endl
,std::string
, etc. This gives you the best control over the namespace scope, and is the preferred approach, but can be tedious to use. - You can add the entire
std
namespace to the local scope, by using the directiveusing namespace std;
at the top of the source file, right below the#include
directives. This is the easiest solution, and the most common, but it loses most of the advantages of having separate namespaces. Most professional programmers avoid this for all but the most trivial programs. - You can add the individual clases or objects to the local scope, by using the
using X::Y
form of the directive, e.g.,using std::cout;
. This lets you use that specific objects without explicit scoping, without polluting your local namespace …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
I noticed a serious bug in the program: you are allocating ptr
based on an uninitialized value for n
, which means that the size of ptr could be nearly anything. You'll need to read in n
first, then allocate ptr
, and only after that should you read in the first element of ptr
. This also means that you'll need to free()
the buffer pointed to by ptr
on each iteration of the outer loop.
Interestingly, I compiled and ran this (under Windows 7, MinGW GCC 4.4.1 with -Wall) and got dinged for not including <stdlib.h>
(required for calloc()
). Once I fixed that, I was able to get it to compile, but it would fail with a protection violation on this line:
scanf("%d",&ptr[0]);
I fixed the format string to
scanf("%ld", &ptr[0]);
and it read in correctly at that point.
Oh, and I would strongly recommend adding prompts for each input, so that it is clearer which value is getting set when. I know you know the program, but without some sort of clue, it would be easy to get lost if your entering several iterations.
for(il=0; il<s; il++)
{
printf("n: ");
scanf("%d",&n);
ptr=(long int*)calloc(n, sizeof(long int));
printf("t[0]: ");
scanf("%ld", &ptr[0]);
printf("s1: ");
scanf("%d",&s1);
printf("s2: ");
scanf("%d",&s2);
printf("k: ");
scanf("%d",&k);
/* and so on */
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Odd, I was able to get it to run correctly without any changes (under MinGW GCC 4.4.1). Which compiler are you using?
BTW, the use of the negative operator on zero is has no effect; zero is neither positive nor negative. HTH.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
To get the crux of the problem, take another look at what the for()
loop does in each of it's four parts. Here is a simplified version of the BNF grammar of the for()
expression:
<for_loop> ::= 'for (' <initialization> ';' <conditional> ';' <increment> ')' <body>
Compare this to the while()
loop:
<while_loop> ::= 'while (' <conditional> ')' <body>
The first part is initialization: it let's you perform an action - usually setting a value, but not necessarily - once, and only once, before the loop is ever run. There's no equivalent to this in the while()
loop, so whatever is done in the initialization part of the for()
loop has to be done before the while()
loop begins.
The second part is the conditional, which tests to see if something is true, and if it is, it runs the loop through once. This is exactly the same as the while()
loop's conditional. Therefore, the conditional of the equivalent while()
loop should be exactly the same as the conditional part of the for()
loop.
The third part of the loop, the increment (or control), runs once per iteration, after the body of the loop has run. It is primarily used to make some change that may alter the value of the conditional - it controls when the loop ends (usually). Again, there is no equivalent in the while()
loop, so it has to be added after the end of the body; the …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
That depends on how old the compiler is; if you mean C++Builder XE, for example, that should be fine, as it is a current-day IDE and compiler which has an excellent (if proprietary) GUI library.
However, I would avoid the older MS-DOS Turbo C compiler, if you have any choice in the matter at all. It is now over 20 years old, and badly outdated, both in terms of its capabilities and with regards to the version of the C language it supports. There are much better Windows compilers available for free, such as Pelles C or Code::Blocks, which give full support for 32-bit and 64-bit Windows.
(That goes double for the Turbo C++ compiler, as it predates the C++98 standard which changed the language considerably.)
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
In addition to Trentacle's questions, I would also ask, what compiler are you using, under what kind of system? The reason I ask is because, while a ten million item array is almost certainly excessive, it should be possible to declare and use one under a modern 32-bit or 64-bit compiler - I have no trouble declaring such an array under either Visual C++ 2010 Express or MinGW GCC 4.4.1 x86, for example, and I assume that Pelles C would be able to as well - but an older, 16-bit compiler almost certainly wouldn't be able to declare an array larger than 65535KiB total size.
Also, you fail to mention what it is an array of. Keep in mind that an int
array would require more memory than a char
array of the same size, for example.
As for alternatives, it would depend on the nature of the data being stored in the array. If it relatively sparse - that is to say, most of the values aren't being used, or are set to some default value - it may be possible to use a linked list to emulate a sparse array. If the data is in any way heirarchical, a tree or some other complex structure may be useful for it. If only part of the data is needed at any given point - which is generally the case - It may be possible to use a to keep part of the data on disk rather than …
Ancient Dragon commented: great answer :) +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
First off, while it isn't relevant to your particular issue, I would recommend against using void main()
. According to the C++ standard, the only valid return type for main()
is int
, and while some compilers do accept other return types, it is strictly non-portable.
Speaking of non-portable, the <conio.h>
library is specific to older MS-DOS compilers, and while some newer compilers have versions of it, they are not by any means consistent with each other. In any case, there's no real need to clear the screen, unless you were specifically instructed to by your instructor. If you eliminate the conio.h>
header and the clrscr()
function, you'd have portable code.
Sort of, that is... except for one more minor issue. The newer C++ standard (as of 1998, that is) changed the headers, so that <iostream.h>
should now be just <iostream>
. It also added a system of namespaces, which means you'll need a scope qualifier. The easiest way to have that is to add the line
using namespace std;
just after the header includes. A better way would be to explicitly scope each reference to a class or object in the std namespace, like so:
void bande()
{
std::cout<< "Enter Base number:";
std::cin>>b;
std::cout<< "Enter Exponent:";
std::cin>>e;
}
While it is more work, it gives you better control over the namespaces.
Which compiler are you using, BTW? If you are using the Turbo C++ compiler, I would strongly recommend getting rid of it; it is more than 20 …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
In that case, could you post the exact error message as it appears in the compiler window, including the line numbers? If you could let us know which compiler and IDE you are using, it may help as well.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
I am going to over-step the usual rules about how one is supposed to help people here, but only because I think you need a good example for how to work with structures and strtok()
. While the meanings of the different aspects of this are purely speculation on my part, I think tha this is close to what you want:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 15
typedef struct Packet
{
unsigned int id;
unsigned int arrivalTime;
unsigned int transmissionTime;
unsigned int priority;
} PACKET;
struct
{
size_t message_size;
PACKET* packets;
} Message;
int main()
{
FILE* file;
size_t i;
char packet_description[BUFFER_SIZE];
char *token;
char* textFile = "data_filetest.txt";
if((file=fopen(textFile, "r"))!=NULL)
{
fgets(packet_description, BUFFER_SIZE, file);
sscanf(packet_description, "%u", &Message.message_size);
}
Message.packets = calloc(sizeof(PACKET), Message.message_size);
for(i = 0; i < Message.message_size; i++)
{
fgets(packet_description, BUFFER_SIZE, file);
token = strtok(packet_description, ":");
Message.packets[i].id = atoi(token);
token = strtok(NULL, ",");
Message.packets[i].transmissionTime = atoi(token);
token = strtok(NULL, ",");
Message.packets[i].arrivalTime = atoi(token);
token = strtok(NULL, "\n");
Message.packets[i].priority = atoi(token);
}
fclose(file);
for (i = 0; i < Message.message_size; i++)
{
printf("Packet #%u, Priority %u: ", Message.packets[i].id, Message.packets[i].priority);
printf("transmitted at %u, arrived at %u\n", Message.packets[i].transmissionTime, Message.packets[i].arrivalTime);
}
printf("total message size: %u\n", Message.message_size);
return 0;
}
You'll need to make the appropriate changes to match the actual interpretations of the different fields.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
The structure as given makes no sense; I suspect what you want is more on the order of this:
typedef struct dynamic_array
{
size_t array_size;
int* array;
} DYNAMIC_ARRAY;
The idea here is that you have a size_t
variable to hold the number of elements in the array, and then a pointer which can hold the array itself.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Having taken the time to compile the code and run it, I've found that the error in question occurs on line
104 (and repeated on line 142), where you have an invalid cin.operator>>()
reference:
cin>>Fname>>" " >>Lname;
You cannot have any literals inside a cin>> operation. In this case, the space is unnecessary, anyway, as cin >> automagically breaks the input at whitespace. Thus, this is all you should need:
std::cin >> Fname >> LName;
Note that used the fully qualified version of the std::cin
object; I recommend doing this most of the time, rather than using the using namespace std;
directive. A fully working version of your code using explicit scoping would be:
#include <string>
#include <iostream>
#include "lab_14_head.h"
void showMenu()
{
std::cout<<std::endl;
std::cout<<"********User Menu***************************************************"<<std::endl;
std::cout<<"Enter 1 to play with a void function without parameters "<<std::endl;
std::cout<<"Enter 2 to play with a void function parameters "<<std::endl;
std::cout<<"Enter 3 to play with a value-returning function without parameters "<<std::endl;
std::cout<<"Enter 4 to play with a value-returning function with parameters "<<std::endl;
std::cout<<"********User Fullname***********************************************"<<std::endl;
std::cout<<"Enter 5 to play with a void function without parameters "<<std::endl;
std::cout<<"Enter 6 to play with a void function parameters "<<std::endl;
std::cout<<"Enter 7 to play with a value-returning function without parameters "<<std::endl;
std::cout<<"Enter 8 to play with a value-returning function with parameters "<<std::endl;
return; //no value is returned here
}
//this is a void function without parameters
//it gets two numbers from the user and prints the sum
void fun_1( )
{
//local …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
OK, first things first: I know that you were probably instructed to put the functions in the header file, but in fact you only want the function prototypes declared there; you'll want to put the actual functions in a third file, which would then be linked into the program at compile time.
#ifndef LAB_14_HEAD_H
#define LAB_14_HEAD_H
//This function shows the user menu
#include <string>
void showMenu();
void fun_1();
void fun_2(int x, int y);
int fun_3( );
int fun_4(int x, int y);
void fun_5();
void fun_6(std::string Fname, std::string Lname);
std::string fun_7();
std::string fun_8(std::string Fname, std::string Lname);
#endif
Just how you would do this depends on your working environment and how you are compiling it; which is to say, it works differently for Visual Studio than how it works in Code::Blocks, which is different from how you would do it from the command line, etc.
As for the reasons why you don't want the functions themselves in the header files, this posting gives a thorough, if tongue-in-cheek, explanation for it as well as some historical context.
Now, to address the specific error message in question, let me ask you, does it say what line the error is occurring on? I suspect that it is a namespace issue, but without more information I cannot say for certain.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
On the one hand, I agree with veedoo regarding the use of a general-purpose editor; it is often better to have one editor which you are well-familiarized with, than to jump between different editors based on the language. OTOH, there are always circumstances where you won't be able to use your favorite tools, so being familiar with several may have its place as well.
If I may ask, which compiler are you using? This could influence which IDEs are suitable or available; for example, Code::Blocks can work with several different compilers with little effort, including the MinGW GCC (the default) and the Microsoft and Borland C++ compilers. Others, such as Visual C++, are essentially compiler-specific (it is possible to use it with other compilers, but it is so much work to set up that it's not worth the effort). Also many compilers come with IDEs these days, even strictly C language compilers such as Pelles C.
As for which language to learn first, well, in my arrogant opinion, both C and C++ are languages best learned as one's third or fourth language; you generally want to have a good grasp of basic programming before digging into the lower-level details which C excells at, while C++ is a bit of monster, a giant language which gives you not just the rope to hang yourself with, but the scaffold, trapdoor and lever, too. My experience is that most newcomers can learn a higher-level scripting language, then an assembly …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
I would actually recommend using template specialization and the string::find() method instead:
template<>
bool CustomType<std::string>::Contains(const std::string& literal, bool CaseSensitive)
{
std::string s(literal);
if (!CaseSensitive)
{
for (size_t i; i < s.size(); i++)
{
s[i] = tolower(s[i]);
}
}
return this->find(s);
}
template<>
bool CustomType<char *>::Contains(const char* literal, bool CaseSensitive)
{
std::string s(literal);
std::string self(this);
return self.Contains(s, CaseSensitive);
}
template<typename T>
bool CustomType<T>::Contains(T literal, bool CaseSensitive)
{
throw("Not a literal type.");
}
Note that this works if you have a string for both the template type and the function argument, or a char pointer for both, but not when mixing the two. You would still need to overload the function to get that added functionality, if you want it:
template<>
bool CustomType<std::string>::Contains(const char* literal, bool CaseSensitive)
{
std::string s(literal);
return this->Contains(literal, CaseSensitive);
}
template<>
bool CustomType<char *>::Contains(const std::string& literal, bool CaseSensitive)
{
std::string self(this);
return self.Contains(literal, CaseSensitive);
}
I can't promise that this works, but AFAIK it should be more or less correct.
triumphost commented: Best Idea! I used this without the find because find can't be used on vectors. But Good! =] +5
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Rubberman: To be more specific, for any regular grammar, there is a Deterministic Finite Automaton (DFA) capable of accepting the language described by the grammar. Because DFA are very easy to code, and can be generated automatically, almost every modern language is designed so that the lexemes form a regular language. Thus, it is typical to define the lexical analyzer by creating a regular grammar for the lexemes, and create a DFA to implement it. The approach I demonstrated above is a less formal version of this, but it still works by implementing a DFA; if I were being more formal, I (or the preferably, the OP) would have defined a grammar for the lexemes first, then worked from the production rules step-by-step. Since this is clearly a course assignment, I wouldn't have suggested using a lexer generator, though it is good to point that out.
DFA are not capable of recognizing context-free grammars, which includes pretty much all Turing-complete programming languages (those which aren't themselves context-sensitive, that is; note, however, that the fact that the language's semantics are Turing-complete does not require the language's grammar to be recursively-enumerable). Thus, a parser for most programming languages has to be more complicated than a DFA, requiring the equivalent of a Push-Down Automaton to recognize it. This is why parsers and lexical analyzers are different from each other.
Without more information (say, a pre-defined grammar written in
Sokurenko commented: oh i see now, i can write regular expression for every automata bot not other way :) +2
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
OK, let's start with the basics. In general, the first step in parsing a stream of text is to break the text up into lexemes (tokens), right? So, what you want to do is work out the basic components of the input format, write a simple lexical analyzer to tokenize the input stream, and write your parser to work off of that token stream.
Without more information about the particular file format or language you're parsing, it's hard to say exactly what your tokens would be, but from the example you gave, you might have /
, {.
, .}
, _
and strings of aphanumeric values, as your lexemes. There may be additional production rules that aren't quite so obvious (e.g., what to do with spaces, newlines, and other whitespace), but this seems a likely set of values right now. This would give us a set of tokens and a token structure type something like this:
enum TOKEN_TYPE {INVALID = -1, EOF, FWD_SLASH, OPEN_BRACE, CLOSE_BRACE, UNDERSCORE, STRING};
struct Token
{
TOKEN_TYPE id;
char value[MAX_TOKEN_SIZE];
};
Now you need to work out how to handle the text stream. As Sokurenko seems to have meant to say, the fgets()
function is a good place to start; however, it gets a bit more complicated than that, or at least it can, depending on what (if anything) a newline character means in the given source language or format. Also, while you want to read in the input stream a line at a time, you …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Ordinarily, the best solution for primes under about 1 million would be to use the Sieve of Eratosthenes to generate all of the primes from 2 to the upper bound number. Given that the sieve requires that you start at 2, however, it may not be what your professor is looking for. Still, it is the easiest solution, and simple conditionals can then be applied to get the desired range.
I would recommend using the sieve to generate a table of primes, then go through that table with a separate test to see if a given value was a) in the desired range, and b) matched the requirement that all of the component digits are also prime.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Rather than eliminating code, in this case you need to add a line just above the first while()
statement (line 20):
head = newNode;
This sets the head of the list, which you'll need in order to access the list as it progesses.
There's a problem within the while()
loop itself, as well; rather than setting newNode->link
to NULL, you need to set it to a new node, then progress newNode itself.
newNode = new nodeType;
head = newNode; // initialize the handle for the list
while(!EOF)
{
getline(reeaad,newNode->info);
newNode->link = new nodeType;
newNode = newNode->link;
}
Otherwise, you are simply overwriting the data as it comes in.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
I am somewhat puzzled by the use of this loop to print out the two different strings in card[][]
:
for(int x=0;x<19;x++) {
printf("%c",card[i][x]);
if(card[i][x] == ':') {
fgets(&face[i],3,stdin);
}
}
Wouldn't it be just as easy to use
printf("Enter suit value for %s ", card[i]);
face[i] = getchar();
getchar(); /* clear out the trailing newline */
given that the last character of the strings is known to be the colon?