Author |
Topic: arrays (Read 2391 times) |
|
brock123
Newbie
Posts: 13
|
Q) Write a program that calls the function read_char which reads a set of characters into the array lst and returns the number of elements inserted into the array (lst), The input is terminated by entering the end of line character. The program then reads a character (ch) and an integer (pos) and calls the void function inserts which inserts the character (ch) at a specified position (pos).The new arry (lst) is printed from the main function. This is the solution: #include<iostream.h> int read_char (char lst[]) { int i=0; char x; cout<<"Enter a set of characters :"<<endl; cin.get(x); while (x!='\n') { lst[i]=x; ++i; cin.get(x); } return i; } void inserts (char lst[],char ch,int pos,int & s) { for (int i=s;i>pos;i--) lst[i]=lst[i-1]; lst[pos]=ch; s++; } int main() { int s; int pos; char lst[100]; char ch; s=read_char(lst); cout<<"number of element into the array is "<<s<<endl; cout<<"Enter a character:"<<endl; cin>>ch; cout<<"Enter the position:"<<endl; cin>>pos; inserts (lst,ch,pos,s); for (int i=0;i<s;i++) cout<<lst[i]<<" "; return 0; } but can you solve this program by another way especially this part : void inserts (char lst[],char ch,int pos,int & s) { for (int i=s;i>pos;i--) lst[i]=lst[i-1]; lst[pos]=ch; s++; } thank you.
|
« Last Edit: Jan 2nd, 2005, 5:50am by brock123 » |
IP Logged |
|
|
|
towr
wu::riddles Moderator Uberpuzzler
Some people are average, some are just mean.
Gender:
Posts: 13730
|
|
Re: arrays
« Reply #1 on: Jan 2nd, 2005, 11:07am » |
Quote Modify
|
If you're allowed to use strings ( <string> ) to read the input, you can use std::string str; getline(cin, str); to read a whole line at once and if you want you can copy str.c_str() to your char lst[] (f.i. with strcopy) It's quite possible the computer will do more work, but the code will be shorter and cleaner. And for inserting, you could use the string::insert member function.. You're probably not supposed to do this though, since it probably defeats the purpose of the excersize. A few notes, if you use cin and cout, then you're programming C++. So you ought to use C++ includes, this means #include <iostream> instead of #include <iostream.h> And if you don't declare that you're using the standard namespace (which you can do after the includes section by writing using namespace std; ), you ought to use std::cin and std::cout, rather than without the std:: Just because the compiler accepts it as it is doesn't make it good form.
|
|
IP Logged |
Wikipedia, Google, Mathworld, Integer sequence DB
|
|
|
brock123
Newbie
Posts: 13
|
|
Re: arrays
« Reply #2 on: Jan 2nd, 2005, 2:42pm » |
Quote Modify
|
thank you towr.
|
|
IP Logged |
|
|
|
|