2012-09-13 229 views
0

如何使用getline(cin, input);分割输入字符串以输入变量?我想分裂成这样的字符数组:将字符串拆分为数组C++

char[] = { // What goes here to make it read the input variable and split it into chars } 

有没有办法做到这一点?

那你们都是新帖吗?哪一个最好?这里是凯撒密码代码我需要修改在字符数组来读取输入变量和存储它的字符:

// Test Code ONLY 
// Not A Commercial Program OR A Crypter 
// THIS IS A TEXT CIPHERER 

#include <windows.h> 
#include <cstdlib> 
#include <iostream> 
#include <string.h> 
#include <vector> 

using namespace std; 

int main() 

{ 
    string in; 
    string out; 
    char lower[25] = {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}; 
    char upper[25] = {A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z}; 
    char upcip[25] = {Z,Y,X,W,V,U,T,S,R,Q,P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A}; 
    char locip[25] = {z,y,x,w,v,u,t,s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a}; 
    cout << "Enter PlainText: "; 
    getline(cin, in); 
    // which sample goes here to read the input var char by char, then store the chars in order in a char array in your opinion? 
    return 0; 
} 
+0

你为什么需要这个? 'std :: string :: c_str()'将返回一个指向空终止字符数组的指针。 – jrok

+0

可能的重复[如何在C++中标记字符串?](http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c) –

+0

用代码I更新的OP试图编辑。 – hCon

回答

4

的字符串已经字符数组:

for (std::string line; std::getline(std::cin, line);) 
{ 
    for (std::size_t i = 0, e = line.size(); i != e; ++i) 
    { 
     std::cout << "char[" << i << "] = '" << line[i] << "'\n"; 
    } 
} 
0
string str; 
    std::getline(cin,str); 
    char* pArr = new char[str.size() + 1]; // add 1 for zero element which is the end of string 
    strcpy(pArr,str.c_str()); 

/* 
some actions with pArr, for ex. 
while(*pArr) 
    std::cout << *pArr; // output string on the screen 

*/ 

// updated: release memory obtained from heap 
delete [] pArr; 
+0

不要忘记在完成后删除阵列。而为了异常安全,它确实应该由某种RAII类型来管理,比如'std :: string'。 –

+0

好的,谢谢。我包括内存释放的东西。 –