In-put/Out-put Help.

+2 Robert Kambies · January 24, 2015
Hi Everyone,

I have to write a program that takes a string from the user, and then prints each character in the string on a line by itself preceded by n spaces, where n is the position of the character in the string.

So far i have this but I still am not sure this is the correct way to go with it seeing as I cant get the characters to separate. Any help would be great. Thanks.


#include <iostream>
#include <string>

int main()
{

  std::string name;
  std::cout << "What is your name? ";
  getline (std::cin, name);
 
  std::cout << "\t" << name << "\n";
  std::cout << "\t \t" << name << "\n";
  std::cout << "\t \t \t" << name << "\n";
  std::cout << "\t \t \t \t" << name << "\n";
  std::cout << "\t \t \t \t \t" << name << "\n";
  std::cout << "\t \t \t \t \t \t" << name << "\n";
 
}

Post a Reply

Replies

Oldest  Newest  Rating
0 Val Almosnino · January 24, 2015
Using your code and my name your out put would be

    Val
          Val
               Val

Krootushas is correct you want to use white space and a for loop.
You might look up the relationship between strings and arrays so
your output looks like this:
V
  a
     l

Val.
0 Robert Kambies · January 25, 2015
Hey Val,

What would the code look like using the string and array relationship?  I have been reading up on arrays but I am not sure how to execute it for what I want to do.  I really appreciate the help thank you.

Rob
+3 Jake Scaife · January 25, 2015
Hello,

I have no idea if this helps but It seemed like a fun way to spend a couple mins :D


#include <iostream>
#include <string>
using namespace std;

int main()
{
string userInput;
string whiteSpace = "";

getline(cin,userInput);

for (int j = 0; j < userInput.length(); j++)
{
  cout << whiteSpace << userInput[j] << endl;
  whiteSpace += " ";
}

return 0;
}

Leaves you with:
/images/forum/upload/2015-01-25/eb9d1af1c0e30190673fae3f903f825e.PNG

You have to remember that a string is just an array of characters. Therefore you can fetch string[index] in the same way as any other array.
  • 1

C++

107,087 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator