This question already has answers here:
"std::endl" vs "\n"
(10 answers)
Closed 5 years ago.
Is there a reason to use endl with cout when I can just use \n? My C++ book says to use endl, but I don't see why. Is \n not supported as widely as endl, or am I missing something?
endl appends '\n' to the stream and calls flush() on the stream. So
cout << x << endl;
is equivalent to
cout << x << '\n';
cout.flush();
A stream may use an internal buffer which gets actually streamed when the stream is flushed. In case of cout you may not notice the difference since it's somehow synchronized (tied) with cin, but for an arbitrary stream, such as file stream, you'll notice a difference in a multithreaded program, for example.
Here's an interesting discussion on why flushing may be necessary.
endl is more than just an alias for the \n character. When you send something to cout (or any other output stream), it does not process and output the data immediately. For example:
cout << "Hello, world!";
someFunction();
In the above example, there's is some chance that the function call will start to execute before the output is flushed. Using endl you force the flush to take place before the second instruction is executed. You can also ensure that with the ostream::flush function.
endl is a function not a keyword.
#include <iostream>
int main()
{
std::cout<<"Hello World"<<std::endl; //endl is a function without parenthesis.
return 0;
}
To understand the picture of endl you firstly need to understand about "Pointer to Functions" topic.
look at this code (in C)
#include <stdio.h>
int add(int, int);
int main()
{
int (*p)(int, int); /*p is a pointer variable which can store the address
of a function whose return type is int and which can take 2 int.*/
int x;
p=add; //Here add is a function without parenthesis.
x=p(90, 10); /*if G is a variable and Address of G is assigned to p then
*p=10 means 10 is assigned to that which p points to, means G=10
similarly x=p(90, 10); this instruction simply says that p points to add
function then arguments of p becomes arguments of add i.e add(90, 10)
then add function is called and sum is computed.*/
printf("Sum is %d", x);
return 0;
}
int add(int p, int q)
{
int r;
r=p+q;
return r;
}
Compile this code and see the Output.
Back to topic...
#include <iostream>
//using namespace std;
int main()
{
std::cout<<"Hello World"<<std::endl;
return 0;
}
iostream file is included in this program because the prototype of cout object is present in iostream file and std is a namespace. It is used because defination(library files) of cout and endl is present in namespace std;
Or you can also use "using namespace std" at top, so you don't have to write "std::coutn<<....." before each cout or endl.
when you write endl without paranthesis then you give the address of function endl to cout then endl function is called and line is changed.
The reason Behind this is
namespace endl
{
printf("\n");
}
Conclusion: Behind C++, code of C is working.
Related
I am trying to get a file path from the user in the getPath() function and return the path as a string. I am having trouble because the compiler says i need to use const char's and i dont know how to do that. How would I use const chars and what even are they. Also how do I print them to the console like in the main function.
#include <iostream>
#include <stdio.h>
#include <string.h>
char getPath() {
char path[64];
std::cout << "Input File Name For Debugging:";
gets(path);
std::cout << "Debugging: ";
puts(path);
return path[64];
}
int main(){
char path[64];
int pathlen = strlen(reinterpret_cast<const char *>(path));
//suppost to print the char array
for(int i; i < pathlen; i++){
std::cout << path[i];
}
return 0;
}
Lot's of misunderstandings
1) char is not a string, it's a character
2) An array of chars (e.g. char [64]) is not a string, its an array. It can hold a string but that's a subtly different idea
3) You don't use [64] when you mean the whole array, so return path[64]; is not the correct way to return a string.
4) Don't mix C++ I/O (std::cin, std::cout) with C I/O (puts, gets), it doesn't work reliably, Stick with C++ I/O so
std::cout << "Debugging: " << path << '\n';
not
std::cout << "Debugging: ";
puts(path);
5) You never call your getPath function so of course it doesn't execute
6) You don't initialise your loop variable i in your final loop so it has no predictable value. You should initialise i to 0
for(int i; i < pathlen; i++){
std::cout << path[i];
should be
for(int i = 0; i < pathlen; i++){
std::cout << path[i];
As you can see lots and lots of mistakes for a very short program. I'm going to show two different correct ways to write this program.
So there are two ways to represent a string in C++, there's the C++ way and there's the way that C++ inherits from C. The code you are writing above is trying to do things the C way, so I'll show that first, but actually the C++ way is much much easier. I'll show that second, but it's the way you should do things.
The first way is to use an array of characters to hold the string. But arrays have serious problems in C++. In particular it's not possible to return an array from a function, so your code above was never going to work, even if you'd fixed all the smaller problems. The way you get C++ to 'return' an array is a bit curious and I'm not going to explain it properly (you need to read a good C++ book). What you do is declare the array in the calling function and pass the array as a parameter. Here's your program written using this technique (and fixed of all the other problems).
#include <iostream>
void getPath(char path[], int n) {
std::cout << "Input File Name For Debugging:";
std::cin.getline(path, n);
std::cout << "Debugging: " << path << '\n';
}
int main(){
char path[64];
getPath(path, 64);
std::cout << path << '\n';
return 0;
}
Note I'm using getline to read the string, which is one C++ way to read a string. getline requires that you pass the size of the array it's going to read into, so I've passed that to getPath as well as the array itself.
Now for the easy way. C++ has it's own string type called std::string. You don't need to use tricky arrays at all. And the C++ string type can be returned from a function in the normal way. This makes for much more natural code. To use the C++ string type all you need to do is #include <string>. Here's your program rewritten to use the C++ string type
#include <iostream>
#include <string>
std::string getPath() {
std::cout << "Input File Name For Debugging:";
std::string path;
std::getline(std::cin, path);
std::cout << "Debugging: " << path << '\n';
return path;
}
int main(){
std::string path;
path = getPath();
std::cout << path << '\n';
return 0;
}
Notice this second program is closer to your original code, getPath has a return type, only it's std::string not char, and it has a return statement to return the path. This is the way you should be writing this code, the C++ string type will make writing string code much easier for you.
I have coded a denary to hex converter and am trying to find a way to remove the sprinf built in function as well as the stoi built in function that i used because as i am using c++ more i am told that using namespace std is bad practice but i cannot think of a way of doing this without breaking my program any help would be appreciated.
also i have left my comments in my code for future Questions should i remove these or leave them in when posting thankyou
#include <iostream>
#include <string>
#pragma warning(disable:4996)
using namespace std;
int DecToHex(int Value) //this is my function
{
char *CharRes = new (char); //crestes the variable CharRes as a new char
//sprintf is part of the standard library
sprintf(CharRes, "%X", Value);
//char res is the place the concerted format will go
//value is the value i want to convert
//%X outputs a hex number
//snprintf covers the formatting of a string
int intResult = stoi(CharRes); //stoi is a function in the library
std::cout << intResult << std::endl; //print int results to the screen
return intResult; //returns int result
}
int main()
{
int a;
std::cout << "Please enter a number" << std::endl;
std::cin >> a; //stores the value of a
DecToHex(a); //runs the function
system("pause"); //pauses the system
return 0; //closes the program
}
Stream in C++ already have built in function for converting format like decimal /hexa etc .. so you can just do this :
int main()
{
int a;
std::cout << "Please enter a number" << std::endl;
std::cin >> a; //stores the value of a
std::cout << std::hex; // Set the formating to hexadecimal
std::cout << a; // Put your variable in the stream
std::cout << std::dec;, // Return the format to decimal. If you want to keep the hexa format you don't havr to do this
std::cout << std::endl; // Append end line and flush the stream
/* This is strictly equivalent to : */
std::cout << std::hex << a << std::dec << std::endl;
system("pause"); //pauses the system
return 0; //closes the program
}
Using std::hex in the stream will print the value in hexa. Using std::dec will print the value in decimal format. Using std::octa will print the value in octal format.
You can call any function from the standard library without using using namespace std simply by prefixing the function with std::.
For example, std::snprintf, std::stoi etc..
This question already has answers here:
When I change a parameter inside a function, does it change for the caller, too?
(4 answers)
Closed 7 years ago.
I've been having a problem in c++ where I call a function which assigns some values to things, but those assignments are lost after the function has been completed. Here is my code:
#include <iostream>
#include <string>
using namespace std;
void Input(string a, string b){
cout << "Input a: \n";
cin >> a;
cout << endl;
cout << "Input b: \n";
cin >> b;
cout << endl << "Inputen Strings (still in the called function): \n";
cout << a << " " << b << endl << endl;
};
int main(){
string c = "This didn't";
string d = "work";
Input(c,d);
cout << "Inputen Strings (now in the main function): \n";
cout << c + " " + d << endl;
return 0;
};
So that whenever I run it, (inputting "Hello" and then "World") the program runs as follows:
Input a:
Hello
Input b:
World
Inputen Strings (still in the called function):
Hello World
Inputen Strings (now in the main function):
This didn't work
I don't know why it's only temporarily saving the values. Any help is appreciated!
change your method signature to accept the address of the variables "&"
void Input(string &a, string &b)
without the "&" operator you are just sending copy's of the variable into the function, with the "&" address-of operator you are passing the variables by reference
Pass your strings by reference and that will allow the called function to change them so the variables in the calling function will have the assigned values.
The way you have it passing by value now, you are just sending a copy of the variables so the new values are lost when Input returns.
void Input(string &a, string &b)
{
...
}
I am new in C++. I generally program in C#, so I'm having troubles with arrays and loops. When I try to print content of dynamic array using a loop, it says corrupted requested area... For example I will give it recognize the condition used with content of array but doesn't print content of it:
// Array.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void main()
{
int size=3;
int *p;
int myarray[10];
myarray[3]=4;
p=new int[size];
p[2]=3;
if(myarray[3]==4){
cout << myarray[3] +"/n";
cout << "Why?";
}
else
cout << "Not equal " << endl;
cin.get();
delete [] p;
}
Code looks fine, unless it should be
cout << myarray[3] << "\n";
Not +
The problem is that myarray[3] +"\n".
"\n" represents the memory location of the string "\n".
You are trying to add 4 to that location and printing it. This should give you junk data or a hardware exception (resulting in a coredump) if you are accessing a protected memory location.
To get what (i think) you are asking for do,
cout << myarray[3] << '\n'
While a solution has been given:
cout << myarray[3] << "\n"
the point to get is that myarray[3] is an integer while "\n" is a string and the only way to "add" them together as strings is to first make the integer into a string. The << operator will handle the work of converting myarray[3] into a string, nothing special, and then the second << pumps a new line after it. I personally prefer code like this and find it more flexible, but it may be more that you're looking for at this stage of learning:
printf("%i\n", myarray[3]);
where printf searches for flags and loads in the other arguments as strings and outputs it in one command.
So I am currently learning C++ and decided to make a program that tests my skills I have learned so far. Now in my code I want to check if the value that the user enters is a double, if it is not a double I will put a if loop and ask them to reenter it. The problem I have is how do I go about checking what type of variable the user enters, ex- if a user enters a char or string, I can output an error message. Here is my code:
//cubes a user entered number
#include <iostream>
using namespace std;
double cube(double n); //function prototype
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
double user;
cin >> user; //user entering the number
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
return 0;
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}
Edit: I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.
Safe C++ Way
You can define a function for this using std::istringstream:
#include <sstream>
bool is_double(std::string const& str) {
std::istringstream ss(str);
// always keep the scope of variables as close as possible. we see
// 'd' only within the following block.
{
double d;
ss >> d;
}
/* eat up trailing whitespace if there was a double read, and ensure
* there is no character left. the eof bit is set in the case that
* `std::ws` tried to read beyond the stream. */
return (ss && (ss >> std::ws).eof());
}
To assist you in figuring out what it does (some points are simplified):
Creation of a input-stringstream initialized with the string given
Reading a double value out of it using operator>>. This means skipping whitespace and trying to read a double.
If no double could be read, as in abc the stream sets the fail-bit. Note that cases like 3abc will succeed and will not set the fail-bit.
If the fail-bit is set, ss evaluates to a zero value, which means false.
If an double was read, we skip trailing whitespace. If we then are at the end of the stream (note that eof() will return true if we tried to read past the end. std::ws does exactly that), eof will return true. Note this check makes sure that 3abc will not pass our check.
If both cases, right and left of the && evaluate to true, we return true to the caller, signaling the given string is a double.
Similar, you check for int and other types. If you know how to work with templates, you know how to generalize this for other types as well. Incidentally, this is exactly what boost::lexical_cast provides to you. Check it out: http://www.boost.org/doc/libs/1_37_0/libs/conversion/lexical_cast.htm.
C Way One
This way has advantages (being fast) but also major disadvantages (can't generalized using a template, need to work with raw pointers):
#include <cstdlib>
#include <cctype>
bool is_double(std::string const& s) {
char * endptr;
std::strtod(s.c_str(), &endptr);
if(endptr != s.c_str()) // skip trailing whitespace
while(std::isspace(*endptr)) endptr++;
return (endptr != s.c_str() && *endptr == '\0');
}
strtod will set endptr to the last character processed. Which is in our case the terminating null character. If no conversion was performed, endptr is set to the value of the string given to strtod.
C Way Two
One might thing that std::sscanf does the trick. But it's easy to oversee something. Here is the correct way to do it:
#include <cstdio>
bool is_double(std::string const& s) {
int n;
double d;
return (std::sscanf(s.c_str(), "%lf %n", &d, &n) >= 1 &&
n == static_cast<int>(s.size()));
}
std::sscanf will return the items converted. Although the Standard specifies that %n is not included in that count, several sources contradict each other. It's the best to compare >= to get it right (see the manpage of sscanf). n will be set to the amount of the processed characters. It is compared to the size of the string. The space between the two format specifiers accounts for optional trailing whitespace.
Conclusion
If you are a beginner, read into std::stringstream and do it the C++ way. Best not mess with pointers until you feel good with the general concept of C++.
There is no suitable way to check if a string really contains a double within the standard library. You probably want to use Boost. The following solution is inspired by recipe 3.3 in C++ Cookbook:
#include <iostream>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
double cube(double n);
int main()
{
while(true)
{
cout << "Enter the number you want to cube: ";
string user;
cin >> user;
try
{
// The following instruction tries to parse a double from the 'user' string.
// If the parsing fails, it raises an exception of type bad_lexical_cast.
// If an exception is raised within a try{ } block, the execution proceeds
// with one of the following catch() blocks
double d = lexical_cast <double> (user);
cout << "The cube of " << d << " is " << cube(d) << "." << endl;
break;
}
catch(bad_lexical_cast &e)
{
// This code is executed if the lexical_cast raised an exception; We
// put an error message and continue with the loop
cout << "The inserted string was not a valid double!" << endl;
}
}
return 0;
}
double cube (double n)
{
return n*n*n;
}
sscanf can do what you want; it returns the number of arguments properly processed. This should get you started:
//cubes a user entered number
#include <iostream>
#include <cstdio>
using namespace std;
double cube(double n); //function prototype
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
string user;
cin >> user; //user entering the number
// Convert the number to a double.
double value;
if(sscanf(user.c_str(), "%lf", &value) != 1)
{
cout << "Bad! " << user << " isn't a number!" << endl;
return 1;
}
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
return 0;
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}
Other methods posted in other answers have their advantages and disadvantages. This one has issues with trailing characters and isn't "C++"-y.
I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.
You can fall back on C and use strtod
You program reads in a string and then passes it to a function that attempts to convert the string into double.
bool is_double(const char* strIn, double& dblOut) {
char* lastConvert = NULL;
double d = strtod(strIn, &lastConvert);
if(lastConvert == strIn){
return false;
} else {
dblOut = d;
return true;
}
}