0

How do I scan a string character by character and print each character in a separate line, I'm thinking of storing the string in an array and use the for loop for printing, but I don't know how.... please help !!!

here is my code :

#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
  string str;
  char option;

  cout << "Do you want to enter a string? \n";
  cout << " Enter 'y' to enter string or 'n' to exit \n\n";
  cin >> option ;

  while ( option != 'n' & option != 'y')
  {
    cout << "Invalid option chosen, please enter a valid y or n \n";
    cin >> option;
  }

  if (option == 'n')
    return 1;
  else if (option == 'y')
  {
    cout << "Enter a string \n";
    cin >> str;
    cout << "The string you entered is :" << str << endl;
  }

  system("pause");
  return 0;
} 
SleuthEye
  • 14,379
  • 2
  • 32
  • 61
prodigy09
  • 23
  • 1
  • 1
  • 4

3 Answers3

6
for (int i=0; i<str.length(); i++)
    cout << str[i] << endl;

that's it :)

floppydisk
  • 248
  • 3
  • 11
2

You can simple do this to access string char by char

for(int i=0;i < str.length();i++)
   cout << str[i];
Murtaza Zaidi
  • 599
  • 3
  • 14
1

There are at least three options to do it. Using ordinary for loop, and using <algorithm> library's functions copy or for_each:

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

void f( char c) {
    c = c + 1; // do your processing
    std::cout << c << std::endl;
}

int main()
{
    std::string str = "string";

    // 1st option
    for ( int i = 0; i < str.length(); ++i)
    std::cout << str[i] << std::endl;

    // 2nd option
    std::copy( str.begin(), str.end(), 
                       std::ostream_iterator<char>( std::cout, "\n"));

    // 3rd option
    std::for_each( str.begin(), str.end(), f); // to apply additional processing

    return 0;
}

http://ideone.com/HoErRl

4pie0
  • 29,204
  • 9
  • 82
  • 118