Solved

Problems: building simple programs

Posted on 2004-04-14
17
997 Views
Last Modified: 2007-12-19
Hi,

Every time I try to write a simple C++ program, something goes wrong. I built a VERY simple C++ program involving arrays.

Something seems to go wrong everytime I execute my program.


Of course you'd want the details so here it is:

1. OS used (God knows why you'd want this):  Win XP
2. Compiler used: Microsoft Visual C++ 6.0
3. Code compiled:
**************************************************************************************
#include <iostream.h>

int main(){
      int part[4];
      for(int i=0; i<5; i++){
            cout << "Enter price of part " << i+1 << ": ";
            cin >> part[i];
      }
      cout << "\n\n\n\t\t\t Prices of the parts are:\n";
      for(int j=0; j<5; j++){
            cout << "The price of part " << j+1 << " is " << part[j] << endl;
      }
      return 0;
}
**************************************************************************************
4. Name of project: Junk (exe file: Junk.exe)
5. What seems to happen: The program runs perfectly until the end
6. What happens at the end:
      - An error is returned: Unhandled exception in Junk.exe: 0xC0000005: Access Violation
      - When I click 'OK', another message box appears: "Find Source: Please enter the path for CRT0.C"
        and a folder tree is displayed.
      - I tried searching for the file. Since I couldn't find it, I clicked Cancel.
      - Then the program disassembly starts and the program is displayed in assembly language

I tried rebuilding the program again but the same error is returned. I shredded the project and tried to stat afresh but the

same error was returned over and over again.

Please note that this error is returned only when I try to compile the specified code. You might think there is something

wrong with the code (You're wrong!): When I try to compile the code below, "You entered one" or "You did not enter one" is

not displayed!

**************************************************************************************
#include <iostream.h>
#include <stdlib.h>                              // Marked

int main(){
      int no;
      cout << "Enter a number: ";
      cin >> no;
      if (no==1){
            cout << "You entered one";
      }
      else{
            cout << "You did not enter one";
      }
      system("PAUSE");                        // Marked
      return 0;
}
**************************************************************************************

(OR)

**************************************************************************************
#include <iostream.h>
#include <stdlib.h>                        // Marked

int main(){
      int no;
      cout << "Enter a number: ";
      cin >> no;
      if (no==1){
            cout << "You entered one\n";      // A 'slash n' added
      }
      else{
            cout << "You did not enter one\n";// A 'slah n' added
      }
      system("PAUSE");                  // Marked
      return 0;
}
**************************************************************************************
[Without the marked lines, the program exits as soon as it is executed]

But the missing lines are displayed when I compile the following code(!):
**************************************************************************************
#include <iostream.h>
#include <stdlib.h>

int main(){
      int no;
      cout << "Enter a number: ";
      cin >> no;
      if (no==1){
            cout << "You entered one" << endl;// An 'endl' added
      
      else{
            cout << "You did not enter one" << endl;// An 'endl' added
      }
      system("PAUSE");
      return 0;
}
**************************************************************************************

Please tell me what to do. If my description is not clear, please ask for clarifications.

Thanking you for your time,

Ram
0
Comment
Question by:ram_einstein
  • 5
  • 5
  • 4
  • +3
17 Comments
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 65 total points
ID: 10822200
change

>> int part[4];

to

   int part[5];

and try again.

Also you should replace

#include <iostream.h>

by

#include <iostream>
using namespace std;


Regards, Alex
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10822214
Hi ram_einstein,
> int part[4];
>      for(int i=0; i<5; i++){

Declare your array as
int part[5];

as you're traversing with 0,1,2,3,4 = 5 times.

>cout << "Enter price of part " << i+1 << ": ";

Check if you need to bracket i+1:

cout << "Enter price of part " << (i+1) << ": ";


Cheers,
Stefan
0
 
LVL 13

Assisted Solution

by:SteH
SteH earned 60 total points
ID: 10822263
To put some light on the exiting of your code:

When creating command line applications under VC++6.0 you can run them in 2 modes:

Using Go: Page with an down arrow or F5.
This uses the debugger and attaches your program to it. When finished with execution the command line window is removed immediatly. But you can stop the program anywhere using breakpoints.

Using Execute Program: Exclamation mark or Ctrl+F5
The program starts in a command line window. Upon termination you are forced to press a key before the window disappears. But to get into the debugger is more difficult. (Only at access violations, failed asserts or using asm int 3 to force a breakpoint.
0
 
LVL 2

Author Comment

by:ram_einstein
ID: 10823935
Hi itsmeandnobodyelse,

Thanks a lot for correcting my arrays problem. part[5] works perfectly fine!

> Also you should replace
> #include <iostream.h>
> by
> #include <iostream>
> using namespace std;

Why? I usually get the error 'std is not a namespace or does not exist'. Besides, what is a namespace?
##############################################################################
Hi stefan73,

Thanks for explaining why I need 5 slots (0,1,2,3,4). I don't need to put the i+1 in brackets though.
##############################################################################
Hi SteH,

You are absolutely right about the exiting. Ctrl+F5 works perfectly! But what bothers me is the the compiled executable file (in /debug) exits before it displays the output. Why? It doesn't have a debugger attached to it! I also noticed that running it from commnd.com (I think equivalent to Ctrl+F5) displays the output correctly. I have one more question: where does the function system() [Defined in stdlib.h] send the enclosed command? To command.com? Then where is pause defined? Is it an internal command.com command?
##############################################################################

Thanking you all,

Ram
0
 
LVL 13

Expert Comment

by:SteH
ID: 10824151
PAUSE is a system command which you can execute on any command line. It is useful only for batch scripts where it is needed to wait for user input. (Like displaying some results before newer ones erase the screen.) Does the compiled file still exit before displaying when the error with the array length is solved? output is first put into a buffer before it is actually displayed. Either using flush,ending the app or at the decision of the OS the buffer content is actually written. (In the help to system it says that all buffers should be flush using fflush or _flushall before calling system!)

A namespace is a capsulation for function names. It allows to define function/variable names you like which don't effect other functions of the same name in other namespaces. So you can have std::cout and cout defined simultaneously. To access a variable which was defined inside a namespace you must make this namespace globally available with "using namespace" or use the scope resolution operator::.  If using namespace std; doesn't give you any conflicts just use it. Only otherwise you need to specify for each function/var std:: before it.
0
 
LVL 13

Expert Comment

by:SteH
ID: 10824168
The message std is not a namespace or does not exit might come from the fac tthat you included "iostream.h" and not iostream. Only latter is using namespace std for its declarations.
0
 
LVL 2

Expert Comment

by:guntherothk
ID: 10824266
re: missing output

You'll find the output is printed, but the window closes so quickly you can't perceive it.
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 10824283
>> I usually get the error 'std is not a namespace or does not exist'

You get that error if  Standard Template Library (STL) that came with the C++ Standard in 1998 isn't properly installed to your environment. Or if the Compiler couldn't handle the C++ Standard.

>> Besides, what is a namespace?

With namespaces a set of classes or names can be used even if you have same name in a different class.

// one.h
namespace one
{
    char func(char);
    class String { ... };
}

// somelib.h
namespace SomeLib
{
    class String { ... };
}

Now the class names will not clash because they become one::String and SomeLib::String, respectively.

Regards, Alex



0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 9

Expert Comment

by:jhshukla
ID: 10824819
**************************************************************************************
#include <iostream.h>

int main(){
     int part[4];
     for(int i=0; i<5; i++){
          cout << "Enter price of part " << i+1 << ": ";
          cin >> part[i];
          $$$$$$$$$$$$$$$$$$$$ Error: you are accessing part[4] during the last iteration. max valid index is (SIZE-1)
          $$$$$$$$$$$$$$$$$$$$ use: for(i-0; i<4; i++)
     }
     cout << "\n\n\n\t\t\t Prices of the parts are:\n";
     for(int j=0; j<5; j++){
          cout << "The price of part " << j+1 << " is " << part[j] << endl;
          $$$$$$$$$$$$$$$$$$$$ Same error repeated here.
     }
     return 0;
}
**************************************************************************************
#include <iostream.h>
#include <stdlib.h>                         // Marked

int main(){
     int no;
     cout << "Enter a number: ";
     cin >> no;
     if (no==1){
          cout << "You entered one";
     }
     else{
          cout << "You did not enter one";
     }
     system("PAUSE");                    // Marked
     return 0;
}
.....
>> But the missing lines are displayed when I compile the following code(!):
.....
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
output to screen is an expensive procedure. to save time output is stored until it grows to certain size and then is actually printed to screen. the use of std::endl (or std::flush) forces the output to be displayed when that particular cout is executed. "\n" served that purpose in C.
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

**************************************************************************************
>> [Without the marked lines, the program exits as soon as it is executed] $$$$$$ NOT a C/C++ or MSVC6 problem.
$$$$$$ you will have to change settings for your command prompt window; you find something like "close on exit". uncheck that box.
$$$$$$ btw, if you run the program at command line (open cmd window; goto %projDir%\Debug; run the exe) the window won't close.

But the missing lines are displayed when I compile the following code(!):
**************************************************************************************
0
 
LVL 2

Author Comment

by:ram_einstein
ID: 10840293
Thanks a lot all of you. But I am still not convinced that my compiler is fine. What is wrong with this?:
##############################################################################
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>

int main(){
      clrscr();                                                                      // Marked
      randomize();                                                               // Marked
      int actual = (int)(rand()%100), input=0, flag=0;
      cout << "Welcome to the number guseening game\n";
      cout << "You have 6 chances to guess the number\n";
      for(int i=1;i<=6;i++){
            cout << "Chance " << i << ": ";
            cin >> input;
            if (input>actual){
                  cout << "Try entering a lower number\n";
            }
            else if (input<actual){
                  cout << "Try entering a higher number\n";
            }
            else if (input==actual){
                  cout << "Correct!" << endl;
                  flag=1;
                  break;
            }
      }
      if(flag==0){
            cout << "Sorry. The actual number was " << actual;
      }
      system("PAUSE");
      return EXIT_SUCCESS;
}
############################################################################

My compiler flashes errors for the randomize() and the clrscr() functions. Withiout the marked lines, the program runs perfectly (except the random number is the same evey time!)

Please tell me what's wrong.

Reagrds,

Ram
0
 
LVL 13

Assisted Solution

by:SteH
SteH earned 60 total points
ID: 10840312
randomize I haven't found as C function. To set a seed for the rand function use
srand (time (NULL));
0
 
LVL 13

Assisted Solution

by:SteH
SteH earned 60 total points
ID: 10840366
And clrscr () I can't find in the help of VC++6.0 SP5. CLS would be an allowed system command so you can try
fflush ();
system ("CLS");
instead.
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 10840377
You may use

  sytem("cls");

instead of clrscr() that seems to be missing on most platforms.

>> except the random number is the same evey time

As STeH already told you, rand() needs an initializing number that could be given by srand()  ('set rand' i suppose). To make this initial number really randomized normally a time function is used to get the current time what gives a reasonable odd number.

Regards, Alex

0
 
LVL 2

Author Comment

by:ram_einstein
ID: 10847666
Hi all,

Thank you all for suggesting system("CLS") instead of clscr. But I still don't understand one thing:
What is srand (time (NULL));? What is the syntax have to do with time? Please tell me how to use the srand function.

Thanking you all once again,

Ram
0
 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 65 total points
ID: 10848543
>> What is srand (time (NULL));? What is the syntax have to do with time? .

srand(unsigned int seed) is an initializing function for rand().  Depending on the value of 'seed' successeve calls to rand() will produce a different sequence of randomized nummers. or othere way round if you seed always using same seed number you'll get the same seguence of 'random' numbers. Thus, to get a real 'random' sequence you need a random seed number. The most easiest way - but not the best - is to use the current time value (in seconds) that you get using time(NULL). It is - as far as i know - the number of seconds elapsed since 01.01.1970 00:00.  So you see, it isn't acutally a 'random' number, and shouldn't used for encrypting purposes. However, to get a different sequence of numbers for a test scenario it is good enough.

>> Please tell me how to use the srand function

Before calling rand() - mostly within a loop - you should call srand(seed); by either setting seed to an odd number like 675574281 then always getting same sequence of rand() numbers or to a 'random' number like time(NULL) or maybe a user input.

Regards, Alex

0
 
LVL 2

Author Comment

by:ram_einstein
ID: 10852137
Thanks itsmeandnobodyelse! Now I understand that I have to find some event that occours randomly and tell that event to return a number to srand() function to create a perfectly random number. I have one last question: Where (in which header file) is the time() fuction defined? Can you think of an event that occours more randomly than the time the program is run?

Thanks a lot for everything you've done so far. Points split between itsmeandnobodyelse and SteH.

Regards,

Ram
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 10852254
>> (in which header file) is the time() fuction defined

use
#include <time.h>

>> Can you think of an event that occours more randomly than the time the program is run

I don't think that other seed numbers will generate 'better' sequences but that the time in seconds isn't sure enough to get decrypted. If i know that you wrote your prog in April 2004 i had to 'try' only some millions of seed numbers instead of 4 billion numbers (10^9). Furthermore any object and any executable doesn't hide the build and compile date, so if you know the algorithm, you have to try only a few seed numbers.
To overcome this, you have various possibilities:

- i mean to remember that modern processors like PentiumIV or Athlon have a real built-in randomizer function, that could be called by an assembler call.
- you may use GetTickCount() on Windows systems, multiply it with any odd number and take only the odd digits, ....
- you may use ftime (#include <sys/timeb.h>) where you get milliseconds also, seed srand() using any 4byte-extract of struct time_b, AND take the first rand() number for another seed.

You see as long as you don't use srand(time(NULL)) it is nearly impossible to evaluate your seed number by accident or to decrypt any of your passwords. However, if you need it for text encryption rand() numbers are not good enough as there are only 2^32 different sequences.

Regards, Alex
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now