2014-09-27 113 views
0

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

这里是我的代码:

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

请妥善格式化您的问题。 – XDnl 2014-09-27 18:25:01

+0

stdio.h中定义的c中的getchar()函数在C++中运行良好,可逐字符读取输入字符。 http://stackoverflow.com/questions/3659109/string-input-using-getchar – 2014-09-27 18:34:24

回答

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

就是这样:)

+0

谢谢allot :) – prodigy09 2014-09-27 20:55:51

0

你可以简单的这样做是为了通过字符访问字符串字符

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

有至少三个选项来做到这一点。使用普通回路,并使用<algorithm>图书馆的功能复制的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