You tell us..? we're not mind readers.
What problem are you having? does it compile? if not, what error message(s) do you get?
You tell us..? we're not mind readers.
What problem are you having? does it compile? if not, what error message(s) do you get?
Put the single character into a short string.
Easy isn't it?
...
yeah but the thing is everywhere I had used a char variable, so it would be difficult changing them all. Anyway I got an idea. I will copy the contents of the char to a string.
And then output it.
I bet you never thought of doing it like that, eh, Salem :icon_rolleyes:
That kind of error usually means you've missed out a definition somewhere - For example, if you've declared something in a header file, such as a function. Elsewhere in your code, you may have called that function, and the linker is unable to find the implementation to go with it.
Without seeing the code which exhibits the problem, there's no way to give any more information than that.
Their use and meaning depends entirely on context. For built-in integral types, they are bitwise operators for bit-shifting operations. Under these circumstances, << means "shift left" and >> means "shift right".
More commonly, you see them in C++ for input and output. Under these circumstances, << means "Outputs to" and >> means "Gets input from"
the two most common examples -
#include <iostream>
int main()
{
int i;
std::cout << "Enter a number: ";
std::cin >> i;
}
Line 6 of the code could be translated to read
"Enter a number: " Outputs to std::cout
Line 7 of the code could be translated to read
variable 'i' Gets input from std::cin
In both cases, the statements are read right-to-left in the code snippet.
AHA!
So that probably explains why this works, even though "per" was declared as a character array:cout<<per<<endl;
Am I on the right track?
Do have good URL for further reading?
The reason it works is because operator<<() is overloaded for all the built-in types to work with std::ostream - including char*. Although as Lerner explained, a character array with no '\0' terminating character doesn't constitute a string, and shouldn't be expected to work the same way.
With operator overloading, its also possible to extend the functionality further with your own types - Have a look here for a little more on operator overloading
http://www.parashift.com/c++-faq-lite/operator-overloading.html
Hi to all
I have a quick question. I am going to fill an array with some inpuit of type char using member function cin.getline. After I fill an array ,I would like to do "for" loop so I need to know what is curently the size of an array. Is it possible. Looks like stupid question because I initialized the array that contains 250 elements (and what I know so far I can't chang ethe size of array, isn't right?). But if I would enter let sey 25 characters. Is the size going to change?Is it possible. If so how may I got the current size of the array. If not what is the best choice to fill an array (maybe vector ?) ,tht will let me know the current size of array
Thank you
The best choice would be a std::string - which is a container specifically designed for holding characters (Far more appropriate to the task than a vector). You can use a std::string with getline() too - eg,
#include <iostream>
#include <string>
int main()
{
std::string str;
std::getline(std::cin, str);
std::cout << str << " length: " << str.length();
}
Check out Bruce Eckel's Thinking in C++, 2nd Edition (Vol.1), available as a free e-book from his website
Here's another article which may make interesting reading - Further detail on the Right-Left rule
http://www.codeproject.com/cpp/complex_declarations.asp
Nothing wrong as far as I can see - as long as you #include <iostream> and have a std namespace declaration.
Did it not compile for you? What compiler are you using?
So its
(***FuncName)()Its legal because functions have no values so the dereferencing asterik has no effect on the function name?
Pretty much, yes.
although it would be noteworthy to say that code like this doesn't pass QA when it comes to readability.
void foo()
{
}
int main()
{
(****foo)();
}
Make sure that when you use the dereference operator, that it actually enhances the readability/meaning of the code, and doesn't detract from it.
You're getting confused between two very distinct topics in C/C++ - Pointers, and function pointers, which are both a rather different kettle of fish.
The reason that function pointers can be handled in such a way as shown in your original post is because of the nature of functions themselves.
in C/C++, you can really only do two things with a function - you may call it, or you may take its address.
Contrast this with a variable, you may also take its address, but you may not call it. In addition to this, unlike functions, you can assign to it, and you can obtain the data it stores.
Since functions and variables are so different, it follows that a pointer-to-function behaves differently to a pointer-to-variable.
Just to put the above into context, when you use the name (identifier) of a function, without the trailing parentheses, the compiler already knows that the function cannot have a value stored, therefore the address of the function is returned instead - the & (address-of) operator is unnecessary.
When you use the name/identifier of a variable, the compiler assumes you wish to obtain its stored value. Hence, if you wish to obtain the address of a variable you must explicitly use the '&' (address-of) operator.
The example you posted using the * (dereference) operator is not legal for the same reasons listed above. this is - a function has no stored data value, …
Its a way of starting an infinite loop which will be stopped using some means other than the condition inside the brackets next to while.
eg,
void somefunc()
{
std::string str;
while(true)
{
std::getline(cin, str);
if( str == "quit" )
return;
else
std::cout << "You Typed: " << str << std::endl;
}
}
IMHO, this kind of idiom is seldom useful - unless you have some compelling reason to do otherwise, you should put an exit condition in the while brackets
There's no difference. manually check to make sure the file exists at the location from which you are trying to open it. Then check the file in notepad to make sure its contents are what you are expecting to read
That's odd - if intellisense is telling you that there's no information available, that suggests its not been disabled (I'm not even sure if you can disable it anyway) I'd suspect either a bug in MSVC++, or something has gone wrong with intellisense's lookup (maybe its database has gotten corrupted somehow?)
Sometimes in MSVC++ 2003 it gets confused by template template types (Especially if you manage to make a typo), and that can cause it to stop working, but usually only temporarily.
Maybe it would be worth creating a whole new Win32 Console project, just in case something 'weird' has happened to your current one. Try writing a 'hello world' app or something simple just to see if it works in there.
I assume the feature you're talking about is MSVC++'s IntelliSense. You should be able to show the list by pressing CTRL+J after the scope operator for classes/namespaces, or the period operator for objects.
Note - This works in MSVC++ .NET 2003 SE. If it doesn't work for your version, check Microsoft's site for IntelliSense.
Bearing in mind that if this is a console application, there's a finite number of characters for any given line which you can output without the code spilling over to the next line, and completely ruining your formatting anyway.
Therefore, it may be simplest to put in an upper limit to the number of lines the program can produce, given the constraints of your environment.
The number of digits/characters that each number has will increase as you get further down the triangle, so you need to take that into account when working out the spacing between each character.
Is it possible to share a printer over a wireless connection? If how, could you please help me. Thanks.
Assuming your OS is some flavour of Windows, then the same service which you use for sharing drives and folders can be used to share printers. On the machine which owns the printer, look in your Printers window, select the properties of the printer, Find the tab labelled "Sharing" - the rest should be self-explanatory.
The type of medium over which you're sharing the resource (Wi-Fi / Ethernet / Bluetooth / etc) is irrelevent, provided the configuration for that connection is setup properly - For Windows NT/2K/XP/etc you need to enable NetBIOS on both computers in order for file & print sharing to work correctly.
NetBIOS usually runs over TCP/IP - there's a setting in the TCP/IP properties in your network configuration which will allow you to enable NetBIOS.
failing this, NetBIOS can also run over Novell Netware's IPX (Used more commonly for older versions of Windows)
Dragon-
I will include my full code below, I had edited out a few things for brevity.
Why do you not construct the Opra_record here:
Opra_record* rec; // = new Opra_record;
Is there a implicit construction somewhere?
Is there any reason why 'rec' is a pointer? It seems to me that you simply want to create an instance of Opra_record .. you don't want a pointer to an object, nor do you want to allocate any memory dynamically with new.
simply typing Opra_record rec;
will invoke the default constructor for Opra_record
Also - Your overloaded >> operator deals directly with Opra_record objects and not pointers.
Edit - I've just noticed you attempt to read your file while !in.eof() - this is almost always wrong - you should read while the fstream is in a good state, and not until you hit an error.
a better statement would be while ( in >> rec )
what is the type of "int position(3) ", different from "int a[3]"
Yes, those are completely different! the line int position(3);
does the same thing as int position = 3;
In case you're wondering why I used the ( ) instead of assignment operator for built-in types is something of a style issue. Personally, I find it more idiomatic to initialise variables using the 'constructor' initialisation syntax rather than the assignment syntax. YMMV, sorry for the confusion :)
but how to use pointer to move the reading postion? point to what?
Imagine file access is like an old fashioned mono-directional cassette tape player (ie, no rewinding!) - the only way to find the position of a chunk of data is to play through the tape from the start, and read each chunk of data sequentially.
The chunk of data you read is always at the "head" position - The tape moves forward, rather than the head (and since you can't rewind, the data which has already passed the head is gone from the stream). You can choose to either store the data at the head or discard it. The tape rolls on once the head has read whatever's at that position. Whatever you do, you *must* read it in order to move the tape on.
here's a quick example of reading the 3rd word in a stringstream (Which is just another 'flavour' of streams - fstreams work in exactly the same way)
#include <iostream>
#include <sstream>
int main()
{
std::stringstream ss("the quick brown fox jumped over the lazy dog");
std::string str;
const int position(3);
for(int i(0); i!=position; ++i)
ss >> str;
std::cout << str;
}
This example outputs the word "brown" - the first 2 words, "the" and "quick" were also read, but discarded, since the only word I was interested in was the 3rd one.
yes,but that is read one line.
how to jump to the second line?
you can't "jump", file access is serial. if you need a certain position, read the first line(s) and discard it/them until you reach the position in the file that you need.
Reading from a file works the same way as reading from any other istream, such as cin:
//read up to newline
std::string str;
std::getline(cin, str);
//read up to whitespace (after a word or character)
std::string str;
cin >> str;
With files, replace cin with the name of your ifstream
Just a few comments, since andor has already pointed out what appears to be the main problem.
usingnamespace std;
typo above, was that a result of colouring in the code? or didn't you copy&paste your code? as a general rule of thumb, never attempt to retype code, because typo's happen - making it hard to give helpful advice - paste it instead.
You've got the variables total and number_buffer declared global - you only need them inside your main() function - you can pass them around to functions if you need to (which you have done), so there's no need for them to be in the global scope. Using global variables is a bad habit, so good design avoids them whenever possible.
The header "stdafx.h" is unnecessary - something which MSVC++ uses when you have precompiled headers enabled. there are loads of hits on google which tell you how to disable precompiled headers.
I'm actually not sure whether I should start with C, jump into C++ or bother learning the language at all. (mainly because of the massive time commitment)
I know I will be learning C++ for the next four years in university. But I also know you shouldn't blindly accept what school teaches you as Gospel. Countless articles on reddit talk are about how Java sucks, schools that teach it put out mediocre hackers, etc. etc.
If you're considering learning C purely as a grounding for C++, then please save yourself the wasted effort and skip 'C'. the two languages sometimes look similar at first glance (C++ inherited alot of the C syntax), but they are fundamentally completely different languages - even the "Hello World" programs you learn to write on day 1 for each language are completely different. (You've probably already written a "Hello World" in C, so here's a quick example in C++ to contrast)
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!";
}
I'd like to backup Grunt's reccomendations for Bruce Eckel's Thinking in C++, and Accelerated C++ by Koenig & Moo. Both excellent beginner's books. Also, C++ Primer by Lajoe, Lippman & Moo comes highly reccomended for beginners.
Francis Glassborow also has a book written for people with no prior programming or computer science knowledge, called You Can Do It. that's also an excellent book, but the compiler & libraries included with the book only work on Windows. (So learning from …
I get a segfault when I run the following. Seems to fail at strcpy.
#include <cstring> using std::strcpy; int main() { char * word = "word"; strcpy(word, "what"); }
If I change char * word to char word[], it's fine. I thought that both declarations effectively do the same thing. What am I missing?
Thanks in advance.
They both do nearly the same thing. The version with a char * word = "word";
creates a pointer to the string literal "word". You cannot assign to or overwrite a literal.
eg, try compiling a program containing the line 5=7;
and you'll get an error.
wheras the version with char word[] = "word";
creates an array of 5 characters in memory; 'w', 'o', 'r', 'd', '\0' . since the array is an object rather than a literal, its contents may be changed.
That depends exactly what part you don't understand. Essentially, your problem seems to be about looping through arrays, and performing some operation on each element. If you're not comfortable with arrays, then do a google search for array tutorials, or check:
http://www.daniweb.com/tutorials/tutorial1732.html
http://www.cprogramming.com/tutorial/lesson8.html
Here's one for 'C' Style strings, which are null terminated arrays of char
http://www.cprogramming.com/tutorial/c/lesson9.html
and one for looping
http://www.cprogramming.com/tutorial/lesson3.html
You might find it handy to bite a smaller chunk off your problem, and create a simple program to solve that. for example, write a program which takes a series of 1's and 0's, and outputs the number of 1's in that series.
Actully that is not true in all the cases.
Which is exactly the point i was making, there are no "always do" or "never do" rules. it depends entirely on the platform you're developing for
Well forgive me for butting in, but here modularity is not an issue since he is not building a Library module but a small program.
As far as writing normal programs are concerned the coder should always be concerned with the best and the fast implementataion wrt to both memory requirements and speed.
But still this is just me, I thought just wanted to let you know.
Any constructive criticisms appreciated.
Modularity doesn't mean that its a library module, he means breaking a program down into smaller, more managable chunks. I agree that it doesn't matter so much for a small toy program, but since maintainability and readability are generally the 2 most important goals for any coder to aspire to (usually far more important than optimum speed & memory usage), its a good habit to get into.
You can't return multiple values from a function, you probably want to pass your variables by reference instead. ie
void ReadInput (int& a,int& b)
{
cout<<"Please enter flavour(1=choco,2=caramel,3=mint) : ";
cin>>a;
cout<<"Please enter number of cartoons(1-20) : ";
cin>>b;
}
Notice the ampersands (highlighted in red), to denote 'pass by reference' ... also, the function has no retun statement, since it is modifying variables elsewhere in the prgram and not returning a value, hence the function's return type is now void
So I try "\-126" and get a compile error. Any other ideas?
"\-126" isn't a char, the double quotes translate that you are attempting to use a string literal, which isn't what you want. There should be no need for the backslash either, since you're not using an escape character.
Just to re-iterate, this is not a C++ issue, this is an implementation-specific font issue. The windows 2000 cmd.exe console uses the "Terminal" font, hence why I got a value of -126 (or 0x82) for the 'é' character. if your implementation uses a different font, there's a strong possibility that the number -126 is not what you need (The code in my earlier post is indifferent to the font)
rambling aside - here is how you might print the é character, if your output uses the Terminal font.
#include <iostream>
int main()
{
char c = -126;
// you could also use 0x82 instead of -126
std::cout << c;
}
or..
#include <iostream>
int main()
{
std::cout << static_cast<char> (-126);
}
You may also be able to change your IDE to use the same font as your console window, although I haven't tested that idea.
I need to insert a "é" and other such symbols. At first I just tried using é straight out in C++ and it returned Θ. So I looked at my character map and did the unicode version \u00E9 where I wanted the é and it still returned Θ. I guess they are using two different standards. Can anyone point me to a list of such common special characters and their c++ encodings? My attempts at a google search have been inconclusive. Thanks :cheesy:
There's nothing standard about extended ASCII characters. the extended ASCII code for that character in your IDE's font is obviously different to the code in your output console's font.
using this code, the character é yields a value of -126 on my system
#include <iostream>
int main()
{
char c;
std::cin.get(c);
std::cout << static_cast<int> c;
}
I know there is a book section, but I'm accually more after personal suggestions/reviews.
Did you actually read the C++ Books thread stickied at the top?
This was my usenet signature for a long time :)
"Computer games don't affect kids; I mean if Pac-Man affected us as kids, we'd all be running around in darkened rooms, munching magic pills and listening to repetitive electronic music." - Kristian Wilson, Nintendo, Inc, 1989
How simple? If you look around, there's usually loads of people listing their homework assignments, a few that I can think of from the top of my head:
Vending machine simulator
Student grades database
Calculator
Noughts and crosses game (AKA "tic tac toe" )
Shopping basket/Restaurant menu/other similar "business order" program.
I didn't say they were identical, I said they were equivalents :)
From a data point of view, these are the same
char* x = "hello";
char x[] = "hello";
In the fact that both create an array of char, size 6, and a pointer.
the difference is that the char* x
version leaves the pointer variable 'x' non-const (so may be reassigned later), whilst the char x[]
version creates 'x' as a const pointer object.
ok, i get it, um.. i dont know how to work the whole pointer for array of strings so i just did this
char firstname[SIZE][MAX_LEN], lastname[SIZE][MAX_LEN];
it seems to be working,but how exactly would i use the pointer instead(char* firstname[] etc)? By the way, thanks so much for the help, this program has been driving me nuts:D
The two forms are almost equivalents (With the one caveat that your form explicitly specifies the size of both array 'dimensions') - although the explanation as to why is not quite so trivial ;)
Essentially, a 'C' String is a series of characters linked in contiguous memory (Plus a null terminating character - that's the '\n' thing).. or, as you know it, an array of char.
However, a variable which holds a 'C' String is not an array but a pointer to the first element of that array.
char* myName = "Fred";
char myNickname[] = "Bloggsy";
// These are equivalent.
With this in mind, a 2D array of characters is not really 2-Dimensional. it is a single array - each element containing a pointer.
So, you have your variable which "contains"(sic) the 2D array (the array of pointers) - but that variable doesn't actually contain an array, it points to the first element.
Hence, the following declarations are equivalent:
char* name[];
char** name;
char name[][];
in every case, the data-type of name is pointer-to-pointer (to char)
Confused? ;)
Ah, OK - the problem is actually your firstname variable - which is an array of char.
firstname[j] is a single character - the problem is that strcmp is expecting a whole string, ie char* or const char*
did you mean firstname to be an array of strings? or do you intend it to be a single string? if it's a single string, get rid of the [j] at the end
for an array of strings, you need to declare firstname as char* firstname[]
Not without seeing how emp or firstname are declared. it would appear from the error that emp[a].last is of type int. Can you post more complete code?
Can a constructor take more than one argument? If so what's the syntax? Is it something like
Staff(std::string s, double x)
Yes, that's perfectly acceptable. there's no arbitrary limit to the number of arguments you can take - although it becomes somewhat unweildy if you provide too many IMHO. (if you've got 6 or more, your code is probably going to look quite ugly - there's almost certainly a better way)
Also, as with member functions, you may define the body of the constructor outside the class declaration, eg,
class Staff
{
vector<Employee> members;
public:
Staff(std::string, double);
Staff(Employee);
};
Staff::Staff(std::string s, double x)
{
// do something here
}
Staff::Staff(Employee e)
{
members.push_back(e);
}
Is there a situation where that would be useful or is it unconventional?
Many situations - you only need to look through the STL to find dozens of examples. The std::vector class has 8 different constructors, some of which take 2, 3 or 4 parameters.
A good example with vectors would be to create a new container based on some elements of an existing container:
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<int> numberList;
numberList.push_back(5);
numberList.push_back(7);
numberList.push_back(19);
std::vector<int>::iterator myIter;
myIter = std::find(numberList.begin(), numberList.end(), 7);
std::vector<int> newNumberList(numberList.begin(), myIter);
}
The snippet above creates a vector of int's holding these numbers - 5, 7, and 19
then the find() algorithm searches for the number 7 in the vector.
when it finds 7, it records the position into myIter
newNumberList …
I'm not trying to be vague. I'm new to programming and don't know all the ins and outs yet. A constructor constructs. That's all I know. As to your original reply, I'm pretty sure I don't want a copy constructor. I think I want to construct a Staff object using an existing vector<Employee>.
Thanks.
When you write a class, C++ already provides you with an invisible default constructor - you don't need to do anything, you don't even need to type it in your code. the constructor will automatically be invoked when you create a staff object, eg,
Staff myStaffList;
Since the only member of your Staff class is a vector<Employee> - a member which doesn't need initialising in order to use it (the vector class itself will have its own constructor which will allow it to be used), you should settle for the default constructor, and concentrate on your member functions for now.
On the other hand, if you later add other values, for example, you might want a string data member to hold the name of your Staff list, you should use a constructor to assign a default value such as "Unnamed Staff List", or a constructor taking a std::string argument to let you specify your own name at the point of construction.
eg,
class Staff
{
vector<Employee> members;
std::string listName
public:
Staff() : listName("Unnamed List");
Staff(std::string s) : listName(s);
};
This above example uses the initialisation list to assign values (preferred method …
OK - you still haven't said anything about what you want your constructor to do, which, I believe is what your original question was about :)
if your vector<Employee> is your only data member, then that doesn't need initialising in order for you to add elements to it. The main purpose of a constructor is to initialise data members and sometimes obtain memory resources for them. It seems from what you've said, that you don't need to do either of those, so you can just make do with the default constructor.
My mind-reading device isn't working today - what are you actually trying to do with the constructor? Construct a Staff object using an existing vector<Employee> ? Construct it using a single Employee object? Make a copy constructor..? Construct it using some other value..?
Bear in mind that the syntax of a constructor is exactly the same as the syntax for any other function.. (Although constructors can have an initialisation list) How would you accomplish what you need with a plain old function?
Hi, I'm new to this C++ stuff. So if anyone can help that would be nice. I have this program to generate a random number and a the user inputs a number from the keyboard to correctly guess the number that the computer randomly chooses. but the numbers are always changing each time, which makes it hard to correctly guess the correct number. So the question is, is it possible to randomly choose a number without it changing each iteration?
Wrap your code in "Code Tags" - makes it easier for everyone to read. :)
Aside from Clinton's excellent spot, there is a slight flaw in your logic...
//Snipped #include's
int main ( )
{
int guess;
char ans;
srand (time (0));
for (int i = 0; i < 100; i++)
{
So... everything after this curly brace (up til the closing brace) gets repeated 100 times.. including:
int random = rand( );
int num = ((random % 100) + 1);
I suggest putting these 2 lines before your loop starts, then you will only be selecting your random number once.
Also, this kind of "guessing game" would look much cleaner if you could say do....while(guess!=num) instead of for...
D'oh, I misread the thread - post contents deleted.
Continuing the conversation with myself... :)
Now that I've had some sleep, It's pretty clear that you don't want your operator<<() to be a member function of Stack, because the syntax to pass to cout is completely counter-intuitive, compared with the rest of STL. The "best" way is for you to make operator<<() a non-member function.
Incidentally, and this is a style issue - if you create the operator as a member function, I think you should use operator>>() (I'll explain in a second...)
ostream & Stack::operator>> (ostream &ost)
{
for (int i=0; i<=top; ++i)
{
ost << arr[i] << ' ';
}
return ost;
}
operator<<() is sometimes known as "put to", whereas operator>>() is respectively "get from"
You would be using your operator to "get" the data in arr[] "from" your Stack.
eg,
Stack MyStackObj;
// ..Populate MyStackObj here..
MyStackObj >> cout;
operator<<() is a member function - you can only pass one parameter at a time to your Stack object using operator<<() - eg,
Stack myStackObj;
myStackObj << SomeValueHere;
If you are merely trying to overload operator<<() then it should be a non-member function.
When defined as a member, the object for which it is called is implicitly "this" (Just like any other member function). The same applies for the any other binary operators which you have defined as members of your stack - you only provide one argument because the "Left-Hand-Side" argument of a binary function is implicit.
Also, being a member function, there is no need for the 'friend' keyword.
void main(){
no, no, no! main() returns an int! :(