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)
{
...
}
Related
This question already has answers here:
Undefined, unspecified and implementation-defined behavior
(9 answers)
Closed 23 days ago.
It seems that member function clear() of string does remove its content, but the removed contents still can be accessed by operator[] . Here's the example that makes me confused.
#include <iostream>
using namespace std;
int main()
{
string input = "Weird";
cout << "Your Input: " << input << "\n";
input.clear();
cout << "Your Input: " << input << "\n";
cout << "Your Input: " << input[0] << input[1] << input[2] << input[3] << input[4] << '\n';
return 0;
}
The results are:
Your Input: Weird
Your Input:
Your Input: eird
Why this is happenning? If example above is normal, what should I do to completely remove its content? (accessing by input[1] should be '\000')
Accessing elements of a string after calling the method clear invokes undefined behavior.
It seems in your case the class std::string uses its internal buffer defined within the class itself for short strings.
After the call of clear the class just set the first character of the buffer with the terminating zero character '\0;.
To check that string was cleared just output its length as for example
std::cout << input.length() << '\n';
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
#include <iostream>
#include <iomanip>
using namespace std;
void getinput(char &first,char &second);
//char getinput(char &first,char &second);
int main()
{
char a[60],b[60];
getinput(a[60],b[60]);
cout << a[60] << " l " << b[60] <<endl;
}
void getinput (char &first, char &second){
cout << "Enter First Input: ";
cin >> first;
cout << "Enter Second Input: ";
cin >> second;
cout << "You Entered " << first << " and " << second <<endl;
}
Everytime i try and make the size of my char arrays bigger so when i call the get input function s0 i can input more then one character is automatically shrinks down in size to one character.
Size of my char array automatically shrinks to 1 after calling a
function
It is the size of an object of the type char.
The parameters of the function have referenced types to objects of the type char.
void getinput(char &first,char &second);
That is it is not a referenced type to a one-dimensional array.
So this call
getinput(a[60],b[60]);
passes to the function references to non-existent scalar elements of two arrays at the index equal to 60.
A simple way to declare the function is the following
void getinput( char *first,char *second );
and the function can be called like
getinput( a, b );
If you want to have a referenced type for the parameters then the function can be declared like
void getinput(char ( &first )[60], char ( &second )[60] );
and called like
getinput( a, b );
Pay attention to that in the both cases of the function declaration it is unsafe because there is no check in statements like this
cin >> first;
whether the user wrote outside the arrays.
Instead of using the operator >> you could apply the member function getline.
For example
std::cin.getline( first, 60 );
cout << a[60] << " l " << b[60] <<endl;
This line doesn't write an array to std::cout, it only writes a single element to std::cout, namely the 61st (which is actually outside of your array).
Instead, you should do this:
std::cout << a << " l " << b << '\n';
Also note that you getinput(char&, char&) function will only read two characters in total from the stream, not two arrays. I recommend implementing the whole thing using std::string instead:
#include <iostream>
#include <string>
int main()
{
std::string a, b;
std::cin >> a >> b;
std::cout << a << " l " << b << '\n';
}
This question already has answers here:
Understanding pointers and local scope [duplicate]
(4 answers)
Closed 6 years ago.
I want to read from user input some numbers and then display them 5 on each line. My code is like this:
#include <iostream>
using namespace std;
const int INPUT_SIZE = 7;
void printValues(int *b) {
int counter = 0;
while (counter < INPUT_SIZE) {
cout << *(b+counter) << " ";
if ((counter + 1) % 5 == 0 && counter>0) {
cout << endl;
}
counter++;
}
cout << endl;
system("pause");
}
int * readValues() {
int b[INPUT_SIZE];
for (int i = 0; i < INPUT_SIZE; i++) {
cout << "Enter element on position: " << i << ": ";
cin >> b[i];
}
return b;
}
int main() {
int* b;
b = readValues();
printValues(b);
return 0;
}
However, when I try to print them, I get some weird numbers which I think are memory locations. How do I print an array and also how do I write a function that returns an array? I have little experience with pointers, as I only coded in Java so far.
Help much appreciated.
Your array, b, is a local variable inside the function readValues.
When readValues exits, the array is destroyed.
The pointer which you return from readValues is invalidated as soon as the function returns. Trying to use it (e.g. by passing it to printValues) is incorrect (formally, it causes undefined behaviour).
You may have caused some confusion by giving the same name b to a pointer variable in main as you do to the array b in readValues. They are entirely separate variables.
If you want to use the same array in your two functions, you need to make sure it lives in a scope which ensures it lives as long as you need it to. This could be by making it a local variable in main.
1 void out3x3(mat3x3 &A)
2 { int i, j;
3 for (i=0; i<3; i++)
4 { if (i==1)
5 cout << "A = | ";
6 else
7 cout << " | ";
8 for (j=0; j<3; j++)
9 cout << A.n[j][i] << " ";
10 cout << "|" << endl;
11 }
12 }
This is a function in a program I'm writing to do matrix manipulations. mat3x3 is a structure for a 3x3 matrix (stored as A.n[3][3]. Instead of 'A' in the output in line 5, I'd like it to output the name of whatever variable I used for the matrix in the calling function.
I only use A, B, and C. I could just write three different functions, but I feel like there should be a better way to do it.
If I say out3x3(B); it will only show A = | |.
I would like this to happen:
out3x3(B);
B = | |
out3x3(C);
C = | |
Thanks for any help.
Names of variables do not exist at run time. They are simply compile time constructs. You would need to do something like change the function to take a std::string argument too:
void out3x3(mat3x3 &A, std::string name)
{
// ...
cout << name << " = | ";
// ...
}
Then call it like so:
out3x3(A, "A");
out3x3(B, "B");
You could then use a macro to make this feel like you're not duplicating the variable name. However, I don't recommend this at all. Instead, I recommend just making your function print out the contents of the matrix (between the |s) and then doing this:
cout << "A = ";
out3x3(A);
The printing of the variable name should be entirely independent of printing out the contents of the matrix. Consider the following analogy:
int x = 5;
cout << x;
This just prints out the value of x, nothing else. If I want to label it, I have to do that manually:
int x = 5;
cout << "x = " << x;
And who knows? Maybe you'll get round to overloading operator<< for your mat3x3 type and soon you'll be doing this:
cout << "A = " << A;
Much prettier.
You could use a macro as a wrapper to call it
#define OUT3X3(mat) \
out3x3(&mat, ##mat);
and change the function prototype to
void out3x3(mat3x3 &A, string name)
The call would be
OUT3X3(A);
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.