adding a char to a cin value

Hello, I have a int value that I take in by cin. And I want to then put that into a function, but I want to add I char letter before that int value, for example, the value taken in is 1234, but the value that is past into the function has to be in the format f1234 , is it possible for me to add the f somehow? I have tried to do 'n' + int val, but that just adds the value of n to the value of the int, so that is not good for my issue. Is this possible?
Yes. You simply have to insert a delimiter to separate the two. Like this:

1
2
3
4
5
char myChar; 
int myInt;

std::cin >> myChar >> myInt;


Input as follows:
 
f 123


or

1
2
f
123
Last edited on
I do not need to take the character in from the user, the f character is set. however how would i put that into the funtion is how i wonder.

int fStreamInital( "this is where I need f" + intVal )

the function has to look like int fStreamInital(f1234)
Last edited on
And what is the type of the f1234 variable?

1
2
3
4
5
6
7
8
9
10
11
12
// Example program
#include <iostream>
#include <string>

int main()
{
    int n = 1234;
    char ch = 'f';
    std::string output = ch + std::to_string(n);
    
    std::cout << output << '\n';
}
Last edited on
If you need to write a function, this should be what you are looking for.
In main you have the user enter a number (n). N is passed to the function combine (or fStreamInitial).
In combine, your preset letter (f) is added to (n) and output to the user.

If you wanted to use a returned value, you could have your function combine the letter and number and return a variable to be used in main.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

void combine(int n)
{
  std::cout << "f"  << n << std::endl;
}

int main()
{
  int n = 0;
  std::cout << "Enter a number: ";
  std::cin >> n;
  combine(n);
 
  return 0;
}


Output:
1
2
Enter a number: 1
f1


1
2
Enter a number: 567890
f567890


If the preset character (f) is being supplied in the form of a variable, you can modify the code as follows (you are basically supplying two variables, from main, to the function, which is then combining them and outputting them).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

void fStreamInitial(char init, int n)
{
  std::cout << init << n << std::endl;
}

int main()
{
  int n = 0;
  char init = 'f';
  std::cout << "Enter a number: ";
  std::cin >> n;
  fStreamInitial(init, n);
 
  return 0;
}

Last edited on
thank you that works
Topic archived. No new replies allowed.