【问题标题】:how to scan a string in C++ [duplicate]如何在 C++ 中扫描字符串 [重复]
【发布时间】:2014-11-22 12:49:56
【问题描述】:

如何逐个字符扫描字符串并将每个字符打印在单独的行中,我正在考虑将字符串存储在数组中并使用 for 循环进行打印,但我不知道如何... .请帮忙!!!

这是我的代码:

#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;
} 

【问题讨论】:

标签: c++ string loops


【解决方案1】:
for (int i=0; i<str.length(); i++)
    cout << str[i] << endl;

就是这样:)

【讨论】:

    【解决方案2】:

    您可以简单地通过 char 访问字符串 char

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

    【讨论】:

      【解决方案3】:

      至少有三个选项可以做到这一点。使用普通的for循环,并使用&lt;algorithm&gt;库的函数copyfor_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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-28
        • 2016-03-24
        • 1970-01-01
        • 2016-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多