How can i add a space to a string that is input by the user.

The += operator is replacing the entire string. I don't really care how its done, i just want to add a space to all strings with an odd amount of characters. What kind of if statement should I use?

#include <iostream>
#include <string>

using namespace std;
string inputstring;

int main()
{
cin >> inputstring;

if((inputstring%2)!= 0)
{

std::string inputstring;
inputstring += " ";

}
std::cout << inputstring;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
using namespace std;

int main()
{
   string inputstring;                // Don't make this a global variable
   cout << "Enter a string: ";        // Let your user know what to do
   // cin >> inputstring;
   getline( cin, inputstring );       // Safer with getline if you want an input with spaces and to clear the input stream
   if( inputstring.size() %2 != 0 )   // Look at the size of the input string   
   {
      inputstring += " ";
   }
   
   // cout << inputstring << '\n';    // Final version
   cout << "[" << inputstring << "]" << '\n';     // Let's see where the spaces are
}


Enter a string: Of Mice and Men
[Of Mice and Men ]



BTW - why do you want to do this?
I got a loooong program to write. This will help me get going. THANK YOU VERY MUCH!
Here is basically the code im trying to write since you asked. Basically encrypting a message.

Define your variables (LCG constants a,c,m ; inputstring, and a key value K0).
Get user input for the input string and key K0.
If the string has odd number of characters add a space at the end.
Write a for loop that runs through the string length, advancing two steps each iteration.
Store the int values of two characters in two int variables left and right.
Write a “for” loop for Fiestel rounds. As specified, this loop will run three times.
Store the value of "right" in a temp variable.
Write a nested “for” loop to run the LCG “K” times; and update “right” value using the LCG function K times in this for loop.
Now use the bitwise operator to calculate the new “right” value = left^right;
Assign left to be equal to old right (stored in temp).
Now output the resultant left and right as hexadecimal, and pad if necessary.
End the program.
NOTE: For first Fiestel loop, K=K0 (user entered); for 2nd Fiestel loop K=K1=K0+1; for third Fiestel loop K=K2=K0+2.


Topic archived. No new replies allowed.