2014-09-27 366 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