C++ Loop

Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

-Fabez-

Thread Starter
Joined
Jul 28, 2008
Messages
1,899
I made a simple program to print a string, then recieve input in C++, however if any whitespace is entered in the cin statement the next cout statement prints the string several times. Below is the code.

Code:
#include <iostream>
#include <string.h>

using namespace std;

int main(){
    string Test;
    int Exit=0;
    do {
       cout << "Example: ";
       cin >> Test;
    } while (Exit != 1);   
}
Any help or advice would be appreciated. Thanks -Fabez-
 
Joined
Apr 30, 2001
Messages
2,636
Examine these examples:

Code:
#include <iostream>
#include <string>
#include <limits>
#include <cstdio>
using namespace std;

int main() {
    string test;
    while (true) {
        cout << "Example1: ";
        cin >> test;
        if (!cin.good()) {
            cin.clear();
        }
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        if (test == "quit") {
            break;
        }
    }
    while (true) {
        cout << "Example2: ";   
        cin >> test;
        fflush(stdin);
        if (test == "quit") {
            break;
        }
    }
    while (true) {
        cout << "Example3: ";
        getline(cin, test);
        if (test == "quit") {
            break;
        }
    }
}
 

-Fabez-

Thread Starter
Joined
Jul 28, 2008
Messages
1,899
Thank you for the code, I now know that I need to use.

Code:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
However I do not know why, can you explain please ? Also is it possible to declare a global variable from inside a function that is located in a class, in a .H file ? Thanks -Fabez-
 
Joined
Apr 30, 2001
Messages
2,636
"cin >>" grabs user input from stdin, but white-space is a delimiter. So, if there's a space for example in the text you enter, cin will stuff everything up to the space in a variable and leave the rest in the input buffer. If you then try to ask for input again, cin is going to look in the input buffer first to see what's left.

So, if you use "cin >>" and want to clear anything left in the input buffer, you can *ignore* as many characters as it takes (up to a newline, which happens when you press enter). This is also basically what fflush(stdin) does. It clears the input buffer.

However, if you use getline(cin, string), it grabs everything on the line and puts it in the string. Then, there's nothing left over.

Now, you also have to test if cin is good() after an operation and then handle the error if it's not. A cin operation could go bad if you are doing cin >> int and type in something that's not an integer for example.
 
Joined
Apr 30, 2001
Messages
2,636
Also is it possible to declare a global variable from inside a function that is located in a class, in a .H file ? Thanks -Fabez-
No, but maybe there's something you want to accomplish that you can do in another way. If you have a simple code example that shows what you'd like to do (even if it doesn't actually work), that might help show what you want.
 

-Fabez-

Thread Starter
Joined
Jul 28, 2008
Messages
1,899
Thank you :D I am trying to include a handle, two constant int's and other variables in the protected section of a class, as shown below for example.

Code:
protected:
     HANDLE ThisConsole = GetStdHandle(STD_OUTPUT_HANDLE);
     const int DefaultTextForeground = WHITE;
     const int DefaultTextBackground = BLACK;
However it will not let me for various reasons, such as me not being able to call a function for example. This means I have to decalare and set thier values in every function I want to be able to use them, so being able to declare them in such a way they can be used from any function after being declared once would be great :D Any help would be appreciated. Thanks -Fabez-
 
Joined
Sep 14, 2005
Messages
919
While that would not work, this does and has the effect you are looking for. The basic idea is to use a constructor (ctor) to initialize any varable data member.

Code:
class foo {

protected:
     HANDLE ThisConsole;
     const int DefaultTextForeground = WHITE;
     const int DefaultTextBackground = BLACK;
};

foo::foo () {

   ThisConsole = GetStdHandle(STD_OUTPUT_HANDLE);
}
 

-Fabez-

Thread Starter
Joined
Jul 28, 2008
Messages
1,899
Thank you, I had to change const int to int and set the value of the default background and foreground in the constructor, other than that it worked great :D I have three questions before I mark this thread solved though.

1) All of the C++ syntax must fall into very general groups, such as declarations, would it be possible to list the catagories C++ or any language's syntax can fall into as well a generic definition for that catagory ?

2) I know a pointer holds the memory address and value of a variable, but why and when should they be used ?

3) I am trying to calculate the number of items in a dynamic array, I have found a way do this, however I do not understand the template part and how it is used, I would be grateful if you could explain please. So far I understand that a template allows for generic coding, but that is all. Below is the code.

Code:
#include <iostream>
template <typename T, int N> char (&array(T(&)[N]))[N];
using namespace std;
int main()
{
  int TestArray[]={1,12,123,1234};
  std::cout << sizeof array(TestArray) << endl;
  cin.get();
}
Thanks -Fabez-
 
Joined
Sep 14, 2005
Messages
919
1) All of the C++ syntax must fall into very general groups, such as declarations, would it be possible to list the catagories C++ or any language's syntax can fall into as well a generic definition for that catagory ?
Assuming I understand the question, C++ has: definitions, declarations, statements, and expressions.

2) I know a pointer holds the memory address and value of a variable, but why and when should they be used ?
>Dynamic memory allocation;
>Sharing the same data via references;
>Pass by reference over pass by value;
>Direct access to memory; pointer arithmetic and function pointers provide alot of things that cannot be done any other way

This list can go on forever. Basically, any time you are using strings in C++, you are using pointers under the hood. Same with new/delete operators, the virtual keyword, and more.
 

-Fabez-

Thread Starter
Joined
Jul 28, 2008
Messages
1,899
Thank you for answering two of my three questions :D With the syntax groups, would it be possible to define the meaning of each group and syntax examples from that group ? Also can you briefly explain templates and the code from question three as the only concept I understand is that a template is used for the generic handling of data types. One final question, is it possible to dynamically execute C++ code ? For example the user can input what they want a variable to be called, its type as well as its value and C++ will create the variable with the given criteria dynamically. Thanks -Fabez-
 
Joined
Sep 14, 2005
Messages
919
3) I am trying to calculate the number of items in a dynamic array, I have found a way do this, however I do not understand the template part and how it is used, I would be grateful if you could explain please.
Yeesh that code is ugly. I recommend not using it as it does not actually define a function, it only declares it and returns the size of the array at compile time.

You can separate the template into sections here:
Code:
template <typename T, int N>
char (&   array   (T(&)[N])  )  [N];
The function declaration, array, takes a single parameter of type T&[N]. The last [N] part of it actually defines it as an array that is returned from this er... declaration. ie; turns it from a T* to a T[N] and returns T[N] as a char&. Because chars are always 1 byte, using it with sizeof effectively gets the sizeof T[N] in bytes.

All of this is resolved at compile time so the template function does not need to be defined. Thus it is like a preprocessor macro. You can demonstrate this by removing the sizeof from your code and calling the function directly. This would create a linker error as the function is, technically, not defined.

I would recommend something like this instead as its defined and nicer to look at:

Code:
template<int N, class T>
void array_size(T (&)[N])
{
	return N;
}
 
Joined
Sep 14, 2005
Messages
919
One final question, is it possible to dynamically execute C++ code ?
No, as all symbolic information in the binary when a C++ program is linked is gone. However, it IS possible to selectively execute instructions or even direct machine code or even modify the machine code during runtime (I did this by calling an array as a function before in MSVC++ 2008 ...I only did it out of curiosity though)

Well...actually, I suppose you CAN do that. They call those programs text editors and compiliers ;)

A "definition" is the actual implemented object, while a declaration simply represents that the object exists somewhere. ie, a function declaration is extern void foo (); while its definition is void foo () {}. This is a basic example, though.

A "statement" is composed of expressions with a defined purpose. Virtually all lines in C++ that end with a ; is most likely a statement.

An "expression" is a little more complex to define. An expression simply computes something and returns a value of sorts. The computing can be done manually by you or by the language itself (ie, if(a) is valid and results to if(a==0). Any test case and math that you perform is an expression. Expressions can also return "side effects" or undefined behavior depending on how they are used. Also, keep in mind, that operators can be overloaded thereby giving "expression" different meanings in the way it is used.

There are different types of expressions, declarations, statements, and definitions. I recommend searching google for more in depth detail on it if you are interested in it.
 
Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 807,865 other people just like you!

Latest posts

Staff online

Top