2012-07-22 101 views
0

我想製作程序來分析程序用戶寫下的文本的每個字母。例如,有人輸入「你好」。有沒有辦法將所有這些字母放在一些數組中?例如,myArray [0] = h,myArray [1] = e,... 謝謝分析用戶輸入C++

+1

你嘗試過'cin.read()'嗎? http://en.cppreference.com/w/cpp/io/basic_istream/read – timrau 2012-07-22 16:00:03

回答

6

您可以像使用數組一樣使用std::string,但它是動態的,知道它的大小,並且更靈活。

//string is like a dynamic array of characters 
std::string input; 

//get a whole line of input from stdin and store it 
std::getline (std::cin, input); 

//you can manipulate it like an array, among other things 
input [0] = 'i'; //now "iello there" 

有關std::string的完整參考,請參閱here

+0

但不是std ::字符串的const char *?或者只是C – 2012-07-22 16:08:09

+0

@ColeJohnson,在內部,'std :: string'有一個'char *',它指向堆保留給你的一個區域。它通過更安全的方法封裝訪問,例如調整數組的大小以適合您的輸入行,而不是可能超出緩衝區。 – chris 2012-07-22 16:09:55

+0

@ColeJohnson並且std :: string不是C風格的字符串都是const。 – 2012-07-22 16:10:25