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;
}
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:
c) You are reading the stream again in
stuff(...)but have already consumed what you wanted to get from the stream inmain().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):
This could be a little more efficient than it is but hopefully it is easy to understand.