2012-12-11 23 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中?

相关问题