2012-12-11 24 views
0

我想獲取用戶輸入並將其放入由空格分隔的cstrings數組中。當我將數組打印到屏幕上時,雖然我什麼也沒有收到。我確信我在做一些愚蠢的事情,但我一直在嘗試不同的方式。任何幫助,將不勝感激。這是代碼。我想要一個由空格分隔的cstrings數組

#include <iostream> 
#include <cstring> 

using namespace std; 

void stuff(char command[][25], int length) 
{ 
    char ch; 


    for(int i = 0; i < length; i ++) 
    { 
     int b = 0; 
     cin.get(ch); 
     while(!isspace(ch)) 
     { 
      command[i][b++] = ch; 
      cin.get(ch); 
     } 

     command[i][b] = '\0'; 
     cout << endl; 
    } 


} 

int main() 
{ 
    char cha[10][25]; 
    char ch; 
    int len = 0; 
    while(ch != '\n') 
    { 
     cin.get(ch); 
     if(isspace(ch)) 
      { 
       len++; 
      } 
    } 
    stuff(cha,len); 
    for(int i = 0; i < len; i++) 
    { 
     cout << cha[i] << endl; 
    } 
    cout << len << endl; 

    return 0; 
} 
+0

請發佈所需的輸出(手寫代碼) –

+0

所以,如果我輸入「john jill jack」,數組長度爲3,包含「john」,「jill」,「jack」 – Igotagood1

回答

2

a)當您首次使用while (ch != '\n')進行測試時,ch不確定。將它初始化爲零或其他東西。

b)你不在while循環中寫入任何值到cha中。也許是這樣的:

int pos = 0; 
while(ch != '\n') { 
    cin.get(ch); 
    if (isspace((unsigned)ch)) { 
     if (pos > 0) { 
      ++len; 
      pos = 0; 
     } 
    } 
    else { 
     cha[len][pos] = ch; 
     ++pos; 
    } 
} 

c)你再次讀取流中stuff(...)但已經消耗你想從流得到main()什麼。

d)此代碼遭受了一些緩衝區溢出和堆棧損壞的機會。或許使用std::vector<std::string>。如果內存耗盡,它會拋出異常,而不是在堆棧上亂七八糟。 也許是這樣的(未經測試):

#include <iostream> 
#include <string> 
#include <vector> 

using namespace std; 

void main() 
{ 
    typedef std::vector<std::string> strvec; 
    strvec cha; 
    std::string s; 
    char ch = 0; 
    while(ch != '\n') { 
     cin.get(ch); 
     if (isspace((unsigned)ch)) { 
      if (!s.empty()) { 
       cha.push_back(s); 
       s.clear(); 
      } 
     } 
     else { 
      s.push_back(ch); 
     } 
    } 
    // don't need to call 'stuff' to null terminate. 
    for (strvec::iterator i = cha.begin(); i != cha.end(); ++i) { 
     cout << *i << endl; 
    } 
    cout << cha.size() << endl; 
} 

這可能是一個小更高效的比它但希望它是很容易理解。

0

您正在閱讀while循環中的整個輸入以讀取主體的長度(字符串數量),但您從不存儲它。後來在stuffcin.get什麼都不會讀。也許在第一個週期中將輸入存儲在cha中?

相關問題