As long as the numbers are recorded as int and not as string or array of chars, getNrDigits provides the correct answer.
cout << getNrDigits(0) << '\n';
As long as the numbers are recorded as int and not as string or array of chars, getNrDigits provides the correct answer.
cout << getNrDigits(0) << '\n';
can any one help me out to identify this problem?
Do you have a time machine that can take you back to 1990? If not, you'll have to wait until someone happens by who remembers how to use your ancient compiler.
What does it help to make a class object as a pointer?
In your code it doesn't matter, but there are a number of reasons you might want or need a pointer. Dynamic allocation comes immediately to mind as a case where you need a pointer.
and also the code crashes when it runs, why cant i use int *k to hold the value?
A pointer has to point somewhere. If you don't explicitly make a local pointer point somewhere then it points to some random address, and any attempt to dereference will likely blow up on you (or worse, not blow up right away).
Ah, that's true. I'm always mixing up C# and VB.NET in my head (usually by including C#isms in VB.NET and getting frustrated when it fails). ;)
Post more code.
The only real problem I see in that line is your query isn't correct. You still need to add single quotes in the query to make string values SQL strings. It helps to copy the string verbatim into Management Studio (or whatever database utility you use), replace the VB.NETisms and run it to verify your SQL syntax. For example, your query would look like this with some dummy data:
SELECT * FROM Security_Ques WHERE Username = someuser and Ques_Index = 0 and Answer = blahblahblah
Looking at it this way, it's obviously incorrect because your strings aren't quoted.
Does anyone have any more experiences that they wouldn't mind sharing?
Mine is a cynical view after having been a system administrator and working with them in many different companies as a consultant. I typically don't expect sys admins to be experts even in the systems they administer. My first foray into the IT field put me in the sys admin position at a reasonably large corporation, and while it was a fabulous learning experience, it highlighted for me that one can do the job without really knowing what you're doing. Further, I regularly go above and beyond as a consultant and end up teaching the system admins of my clients things that I personally think they should already know[1]. And these are not small companies we're talking about, some of my clients are among the largest in the United States or are worldwide. ;)
Ultimately you'll have to satisfy the hiring managers when it comes to skills and experience (which turns out to be easier than the requirements on paper suggest), but my personal opinion is that connections will help far more in getting a job. While the lesser things like tech support and IT grunt will certainly give you experience in the techical and social areas, you'll also meet people who can give you a leg up in advancing to the job you really want.
[1] One thing that consistently comes up and surprises admins is that network shares and the attached physical folder have separate …
The type of file is irrelevant if you're treating it as a sequence of bytes. As long as you don't lose any packets in the transfer, the .exe will be reconstructed correctly and will run on a matching OS.
You have a lot of problems, but the particular problem in edelete() that you're asking about is this:
if((e3.name,dname)!=0)
The code is legal, but you clearly meant to write this:
if(strcmpi(e3.name,dname)!=0)
Anyway, out of the goodness of my heart, I'll fix your code and make it portable so that you can learn what good code (well, semi-good) looks like and hopefully emulate it in the future. I'll keep the code simple and use your basic design except for one modification: instead of a binary file I've serialized to a pipe delimited format in a text file. The more experience I get, the less inclined I am to use binary files, they're often more trouble than they're worth.
Here's the code:
#include <cctype>
#include <fstream>
#include <ios>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
struct Entry {
public:
std::string name;
std::string address;
std::string city;
std::string state;
std::string phone;
std::string serialize() const;
void deserialize(const std::string& s);
friend std::istream& operator>>(std::istream& in, Entry& obj);
friend std::ostream& operator<<(std::ostream& out, const Entry& obj);
};
void AddEntry();
void FindEntry();
void ModifyEntry(bool delete_entry = false);
int main()
{
bool done = false;
std::cout << "\n\t\t\tTELEPHONE DIRECTORY";
while (!done) {
int choice = 0;
std::cout << "\n\n\n\t\t\t*** MENU ***\n";
std::cout << "1. NEW\n";
std::cout << "2. SEARCH\n";
std::cout << "3. MODIFY\n";
std::cout << "4. DELETE\n";
std::cout << "0. EXIT\n\n\n";
std::cout << "Enter your choice: " << std::flush;
if (std::cin.peek() == '\n') {
// Just ignore that can of worms, but allow it without …
i tried posting the code but i am not able to do that .it says my code if formatted incorrectly.......
That error means your code wasn't in a code block. Paste everything in, select it all and hit the tab key. Alternatively, just use the Code button on our editor. It will pop up a code editor box that you can paste your code directly into.
do you mean that code
No, I mean this code:
printf("\nreal number:");
scanf("%d",&x.real);
printf("\nImaginary number:");
scanf("%d", &x.imag);
There's no guarantee that you'll see "real number:" before scanf() blocks for input, which means the user will have no clue what the program is waiting for. If you're not ending the prompt with a newline, I'd recommend calling fflush() to ensure that the prompt will be visible at the right time:
printf("\nreal number:");
fflush(stdout);
scanf("%d",&x.real);
printf("\nImaginary number:");
fflush(stdout);
scanf("%d", &x.imag);
why this happened????????
Probably because you're mixing single character input with formatted input. They don't mix well. To see exactly what characters are being processed, just output ch
immediately after scanf() returns. I'm willing to bet you'll be surprised.
all i need is a way to press Q to end the program!
I was going to post this directly, but it turned into something a bit more serious than I originally intended:
http://www.daniweb.com/software-development/c/code/445012/simple-interactive-menu
when the code is compiled
What code?
Can u pls tell us the errors the errors to b clarified
WHAT ERRORS?! Do you expect us to read your mind?
erm i'm using the compiler in quincy 2005?
Quincy is an IDE, not a compiler. It uses MinGW as a back end, which basically amounts to the GCC compiler. GCC supports C99 under that version, as far as I can tell, but you have to turn it on with a switch. I doubt it's turned on by default, so there you go.
Line 19 - scanf("%c",&ch);
This is overkill (reason).
That's a good reason, but I think I can make it more clear how much work is done. This link is an implementation of fgetc() that I wrote (where fgetc() is the back end to getchar()); it's about 10 lines of straightforward and efficient code. Even if you include the definition of fillbuf(), the whole thing comes in at under 50 lines.
This link is the implementation for scanf(), and this link is the format string parsing helper. I'd estimate that all totaled up you're looking at close to 900 lines of code, and it's not exactly trivial. I spent more time writing printf() and scanf() than the rest of the standard library in that project put together. Naturally not all of it will be hit for a simple format string like "%c", but scanf() is undeniably a heavy function compared to getchar().
is this code will run on all compiler
All C99-compatible or C++ compilers, sure (due to the // style comments). ;) I'd also nitpick your prompts that don't end in a newline because they might not show up on all systems before scanf() blocks for input. But those are minor issues for strict conformance.
getch() don't need press <Enter> every time after user enter any character
and getch() don't print character which user enter it
That doesn't help if getch() isn't supported by the compiler. It's fine in your world of Turbo C, but your code will fail to compile almost everywhere else.
if(ch==69||ch==101)
else if(ch==81||ch==113)
What do 69 and 101 mean? What do 81 and 113 mean? If you force me to memorize ASCII/Unicode or go to asciitable.com to figure out your code then your code is bad. Use the character literals that correspond to what you want, it makes the code much clearer:
if (ch == 'E' || ch == 'e') {
...
}
else if (ch == 'Q' || ch == 'q') {
...
}
You can also use toupper() or tolower() to make a single test:
if (toupper(ch) == 'E') {
...
}
else if (toupper(ch) == 'Q') {
...
}
Holes in your work history are more damning than history in unrelated fields. So yes, add that job.
I have found the solution in other websites that we have to clear the buffer and use cin.ingnore(). Does anyone tell me what does it means ??
cin.ignore() reads and discards characters. cin.ignore(80, '\n')
is roughly equivalent to this loop:
{
char ch;
for (int i = 0; i < 80; i++) {
if (!cin.get(ch) || ch == '\n')
break;
}
}
"Clearing the buffer" means removing pending characters in a line. The reason a line is important is because input from std::cin is nearly always line oriented. You can safely assume that by discarding characters up to and including a newline, that basically ensures that the next character request will force the user to type something.
And also what actually getline() does ?
Really all it does is read characters from the stream up to end-of-file or the specified delimiter and appends them onto the supplied string. A greatly simplified facsimile might look like this:
istream& mygetline(istream& in, string& s, const char delim)
{
char ch;
s.clear();
while (in.get(ch) && ch != delim) {
if (s.size() == s.max_size()) {
in.setstate(ios::failbit);
break;
}
s.push_back(ch);
}
return in;
}
I already posted in my post that i know this solution of implementing it in one cpp file
Header files are a glorified cut and paste mechanism. If you're having trouble with your headers, then manually creating the same effect in a single file can help highlight the problem. You said you fixed it by using a single file, but clearly you made some sort of change that differs from how your compiler would have done it, otherwise the error would persist even using a single file. Here's how the translation unit would look with your headers directly included:
#include<iostream>
using namespace std ;
class FileOne ;
class FileTwo
{
public:
int Test(FileOne One){
return (One.var1+One.var2);}
FileTwo(void);
~FileTwo(void);
};
class FileTwo ;
class FileOne
{
private:
int var1 , var2 , var3 ;
public :
friend int FileTwo::Test(FileOne One);
FileOne(){
var1= 12;var2 = 24;
}
};
int main(){
FileOne one ;
FileTwo two ;
cout<<two.Test(one);
}
The error is still present, and it's much easier to see now that everything is all together in one file. Once you fix the error in a single file, you can break it back up into multiple files. And in this case, the fix is to separate the member function declarations from their corresponding definitions (ie. use a header/implementation file setup).
When you forward declare a class, you only tell the compiler that it exists, not what's in it. So while the declarations are fine, the definition of FileTwo::Test() would need to be deferred until after both classes have been introduced completely:
class FileOne;
class FileTwo
{
public:
int Test(FileOne One);
};
class FileTwo;
class FileOne
{
private:
int var1, var2, var3;
public:
friend int FileTwo::Test(FileOne One);
FileOne()
{
var1 = 12;
var2 = 24;
}
};
// Now this definition will work
int FileTwo::Test(FileOne One)
{
return (One.var1 + One.var2);
}
#include <iostream>
using namespace std;
int main()
{
FileOne one;
FileTwo two;
cout << two.Test(one) << '\n';
}
To facilitate this with multiple files and headers, I'd suggest separating your class declarations and definitions into a header and implementation file. First the header:
// FileTwo.h
#ifndef FILETWO_H
#define FILETWO_H
class FileOne;
class FileTwo
{
public:
int Test(FileOne One);
};
#endif
Then the implementation file which handles definitions:
// FileTwo.cpp
#include "FileOne.h"
#include "FileTwo.h"
int FileTwo::Test(FileOne One)
{
return (One.var1 + One.var2);
}
A function prototype is also called a function declaration. You supplied a function definition.
A definition is also a declaration, but a declaration is not always a prototype. A prototype is the very specific declaration without a body that defines parameters (excluding the case of an empty parameter list), also referred to by the standard as a "prototype declaration":
void foo(void); // No arguments
int max(const int a, const int b);
A prototype-like declaration with empty parentheses is not a prototype:
void foo(); // Declaration (unknown arguments), not a prototype
Definitions introduce a declaration, but follow the same rules and only introduce a prototype if the declaration alone would do so:
// Definition (no arguments), also a prototype (no arguments)
void foo(void) { }
// Definition (no arguments), also a declaration (unknown arguments), not a prototype
void bar() { }
kw42chan's code was correct as far as technically introducing a prototype even though it was done through a definition. But I suspect that it's not correct in terms of the spirit of the assignment, which is to write a prototype independent of the definition:
int max(int a, int b); // Prototype
int main(void)
{
...
}
int max(int a, int b) // Definition
{
...
}
.NET programs aren't compiled to machine code as part of the assembly, they're in an intermediate state (IL assembly language) that the framework needs to compile into machine code. On the first run of an assembly, the just-in-time (JIT) compiler does all of that, which is why it's slower than subsequent executions.
On IDEs I would vote for CodeLite.
Seconded. If you find Visual C++ too heavy then CodeLite is a great alternative to the more oft suggested Code::Blocks on Windows. I'd still recommend Visual Studio if you're on Windows as it's more likely to be used in the professional arena, and experience with the tool will improve your marketability slightly.
@deceptikon: The November update of MSVC11 did add support for, most notably: variadic templates, initializer-lists, and delegating constructors.
Ah, I wasn't aware it was a separate install. That's fantastic. So VC11 is pretty much there in terms of conformance as far as I'm concerned. Now it's just little things. :)
By any chance, were you guys trying to come up for a new update for the site?
The site is updated pretty much daily. But yes, there was a semi-new feature added yesterday in the form of badge linkbacks.
Sadly, I'm unable to touch the production server in an administrative capacity. But looking at recent code changes, it looks like the fix will be as simple as a file rollback from version control.
I'd wager most of our article level scripting will fail to work, given the suspected cause of the problem. It should be a quick fix, but we need to wait for Dani as she's the gatekeeper for the production server. ;)
I'm unable to update our production server, so at the very least we'll need to wait until Dani wakes up. But it looks like there was test code in recent changes that fell through the cracks and needs to be rolled back. It should be a quick fix if that's the problem.
I see a possible issue in recent code changes, but until Dani wakes up we can't confirm it or update production. Just sit tight for maybe another hour and things should be resolved.
Microsoft has implemented almost everything in the standard.
Aroo?
I'd say they've implemented almost everything "easy" in the standard, plus partial concurrency. Variadic templates, constexpr, defaulted/deleted functions, and initializer lists are glaring pain points in VC11 that GCC has. The library is thankfully full featured in VC11, relative to the core language, but that's because they've hacked workarounds in to deal with missing features.
Barring concurrency (admittedly a big deal), GCC is further along in terms of core language support. The library doesn't seem to be up to par though.
I think getting more into it would just confuse you further. Const correctness can be tricky, so it's probably best to just accept this example as an exception to the rule, handle errors as they arise, and wait for a little more experience to faciliate that "aha!" moment.
Constness of a member function only applies to the direct state of the object for its class, so it's completely irrelevant if the non-const hello
calls a member function that changes its own state and not the state of hi
. It would be different altogether if you tried to change where hello
points because that's hi
's direct state. It would also be different if hello
itself were const, because Test() isn't const qualified. Finally, it would be different if hello
were not a pointer because then the state of hello
would be a subset of hi
's state.
You can use negative values in the Add*() methods to represent subtraction from the current value:
datetime.AddSeconds(-1) ' Decrement by one second
I'm guessing you want a form that runs before the main form, but you still want to defer the application thread to the main forum? There are a few ways to do that; one of the simpler ones can be seen in a service configuration utility I wrote that looks something like this:
[STAThread]
public static void Main(string[] args) {
RunApplication(args);
}
private static void RunApplication(string[] args) {
Trace.AutoFlush = true;
Trace.Listeners.Add(new TextWriterTraceListener(TraceFile, "Listener_" + ProductShortName + ".Config"));
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => {
string msg = (e.ExceptionObject as Exception).ToString();
string logMsg = "Fatal Error: Unhandled exception [" + msg + "]";
string usrMsg = "An error was detected at load time. Refer to the trace log for details";
Logger.TraceError(logMsg);
Utility.FatalBox(usrMsg);
if (Application.MessageLoop)
Application.Exit();
else
Environment.Exit(-1);
};
var form = new ServiceConfig();
if (!form.Login()) {
Utility.FatalBox("Login failed.");
} else {
Application.Run(form);
}
}
The main form is ServiceConfig, and it has a method that opens a modal dialog for logging in to an external application. All of this is done before the Application.Run(), so the login dialog appears first and if it fails or is canceled the main form won't show.
It flat won't work (compile errors) because they can't be concantinated like that.
The left operand is a string literal and the right operand is a character literal. It will most certainly compile and run, because the character literal will be interpreted in integer context. Assuming ASCII for the sake of the example, the compiler will see "abc" + 100
, which I'm sure you'll agree is both legal and highly error prone. While the address &"abc"[100]
can be calculated, any attempt to access it will invoke undefined behavior.
If the right operator were also a string then it wouldn't compile because you'd be adding two pointers, which is not legal. I'm assuming that you just misread the question and saw both operands as string literals. ;)
I Just wanna know what happens if we try to do the following in C++: "abc"+'d'
In that particular case, you'd overrun the "abc" array by indexing it beyond the null character at the end. However, whether this is a problem or not depends on how you use the result.
So what's happening? "abc" is converted to a pointer to the first element. Then 'd' is interpreted as an integer value and added to that pointer. The result is the same as any pointer arithmetic of the form p + n
. But because "abc" doesn't have enough characters to handle pointer arithmetic beyond p + 3
, and (int)'d'
is surely much larger than that, you risk undefined behavior.
This is the test program you should have written:
#include <iostream>
int main()
{
std::cout<< "abcdefg" + 4 <<'\n';
}
Not until you elaborate. How are you doing "graphics"?
It depends on the graphics library you're using.
No, ios::out
mode will truncate the file to 0 bytes. You want to use ios::in | ios::out
for update mode. An alternative is this:
Copy the original file to the temporary file
Delete the original file
I think that is easier to get right than updating a single file.
The file's name won't change, you're just overwriting it with updated information. At least, I'm assuming that's how your design works: you have a single database file containing records.
If you have to delete an entry, the simplest method conceptually is to rewrite the file in its entirety without the entry in question. For huge files that can be a performance issue, but for a school project you don't need to concern yourself with huge files.
I wouldn't recommend using strtok() in this case because it modifies the string by way of inserting null characters at the end of each token. This effectively destroys the string for your purposes, so unless you're working with a copy, it's best to stick with a little bit more manual method:
#include <cstring>
#include <iostream>
#include <string>
size_t find_word(const char *s, const char *word)
{
size_t len = strlen(word);
for (const char *p = s; *p; ++p) {
if (strnicmp(p, word, len) == 0)
return (size_t)(p - s);
}
return (size_t)-1;
}
int main()
{
std::string line, word;
std::cout<<"Enter a line of text: ";
getline(std::cin, line);
std::cout<<"Enter a word to find: ";
getline(std::cin, word);
size_t index = find_word(line.c_str(), word.c_str());
if (index == (size_t)-1)
std::cout<<"'"<< word <<"' was not found\n";
else
std::cout<<"'"<< word <<"' is at index "<< index << '\n';
}
Note that I didn't do anything to replace since you only asked about finding the index of the word in question. I assume you already have ideas for doing the replacement once you have that index?
Also note that stricmp() and strnicmp() are not standard functions, so a compiler isn't required to implement them. However, since you used stricmp() in your code, I'm assuming your compiler does implement them.
I'm guessing you didn't read any of the stickies, given that one of them addresses your exact problem.
Oh the shattered hopes and dreams... :)
I'm pretty sure it's in my Daniweb contract somewhere that I have to crush dreams on a regular basis.
@deceptikon, please update or allow Michael to upload an animated pic. anything to swap out that horrendous avatar that he currently has that looks like a cross between a Chihuahua and an an Ostrich. lol...
Haha! But seriously...you think that thing would be better animated? O_o
I am learning C++ on Turbo C++ 3.0
That's a very old compiler, and it's going to hold you back significantly. Unless you're forced to use it for some reason, I'd strongly recommend upgrading to something like Code::Blocks or Visual C++ Express.
And what happens if the original image is 80x80? You still resize it?
A resize is always attempted, regardless of the original dimensions. Honestly, I haven't tested whether an 80x80 animated image flows through (ie. the imaging library treats it as a no-op), or if the resize still behaves the same way regardless of original dimensions. What you suggested may be a workaround.
If yes, you folks are bad guys. ;)
How so? ;)
There's nothing wrong with your code, but use of <iostream.h> suggests an old compiler that may not respect the standard language. What compiler are you using?
Equal ages to what? Do you want groups of employees where each group has the same age? Do you want all employees matching a specified age? You can't write a query with vague terms.