如何逐个字符地扫描字符串并在单独的行中打印每个字符,我想将字符串存储在数组中并使用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;
}
答案 0 :(得分:4)
for (int i=0; i<str.length(); i++)
cout << str[i] << endl;
它是:)
答案 1 :(得分:1)
至少有三种选择。使用普通的 for 循环,并使用<algorithm>
库的函数 copy 或 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;
}
答案 2 :(得分:0)
您可以通过char
简单地访问字符串charfor(int i=0;i < str.length();i++)
cout << str[i];