# string input to an array

• 02-14-2010
keshav_agrawal
string input to an array
a very simple problem : suppose a user gives an input n i take that input in an array say st1[100]
suppose the user gives input and stored in st1[100] as " To err is human. But its no excuse for our casual behaviour."

now it can be clearly seen here that there are two spaces(' ') before "To err...." similarly there are two spaces between "is(' ')(' ')human..." Even after '.' and before "But its..." there are 3 spaces which user entered during providing input.

now what i need is that when this input gets stored into the array st1[] then it shud be stored like dis :

st1[] : T o e r r i s h u m a n . B u t t h i s i s
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

n likewise.... i mean xactly one space between words irrespective how many spaces user enter due to negligence an also exactly one space after punctuation mark ('.').

assistance appreciated...
• 02-15-2010
chameleons
I take it that you want to keep the exact number of spaces in between the words, is it?
• 02-15-2010
keshav_agrawal
i mean when i write in c : gets(st1);

it will take the input in d array st1 from the user. but i don want the string to be stored in d array in d same way as user gave input. I want xactly one space between every word irrespective of how many user gives between words, no space before a string starts, xactly one space after full stop and new word..... like that. hope i made myself clear...
• 02-17-2010
keshav_agrawal
• 02-17-2010
NeonBlack
What have you tried?
Can you describe the algorithm in English or pseudocode?
• 02-26-2010
chameleons
Oh. I got what you mean. You want to eliminate unnecessary spaces that users might have keyed in. Is that right?

Ok, the simplest solution is to use string stream.

Suppose that you captured the user's original input in the array "input". Now the code to trim those unnecessary spaces is as follows:

Code:

```//suppose the result is stored in the char array "st1" char temp[1000]; //put the original input into a string stream istrstream in(input); //initialize st1 to be an empty, non-null string strcpy(st1, ""); while(true){   //read in one word from the stream. it will read until a space is encountered,   //and the space is ignored.   in >> temp;   if(in.good()){     //so now we append this word, and a space to the end of st1.     strcat(st1, temp);   } else {     //if the stream is empty already, it's done.     break;   } } //so now we have an extra space at the end of "st1", we just have to trim it st1[strlen(st1)] = 0;```