0

I am trying to get user input and put it into an array of cstrings separated by a space. When I print the array to the screen though I get nothing. I am sure I am doing something stupid, but I have been stuck trying different ways for a while. Any help would be appreciated. Here is the code.

#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;
}
4

2 回答 2

2

a) ch is undefined when you first test it with while (ch != '\n'). Initialize it to zero or something.

b) You don't write any values into cha in the while loop. Perhaps something like:

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) You are reading the stream again in stuff(...) but have already consumed what you wanted to get from the stream in main().

d) This code suffers from a number of buffer overrun and stack corruption opportunities. perhaps use a std::vector<std::string> instead. If it runs out of memory it will throw an exception rather than make a mess on the stack. Perhaps something like this (untested):

#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;
}

This could be a little more efficient than it is but hopefully it is easy to understand.

于 2012-12-11T09:31:16.693 回答
0

You are reading the whole input in the while cycle in the main to read length(number of strings), but you never store it. Later on in stuff cin.get will read nothing. Maybe store the input in cha during the first cycle?

于 2012-12-11T09:15:11.813 回答