Reputation: 1170
I want to write a program in C or C++ that asks to user to enter the string at run time of different lengths at different times as given by user (either space separated or non space separated) and store it into an array. Please give me the sample code in C and C++ for it.
e.g.
1st run:
Enter string
Input: Foo
Now char array[]="foo";
2nd run:
Enter string
Input:
Pool Of
Now char array[]="Pool Of";
I have tried:
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"enter no. of chars in string";
cin>>n;
char *p=new char[n+1];
cout<<"enter the string"<<endl;
cin>>p;
cout<<p<<endl;
cout<<p;
return 0;
}
But it's not working when the string is space separated.
I have tried this too, but it's not working either.
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"enter no. of chars in string";
cin>>n;
char *p=new char[n+1];
cout<<"enter the string"<<endl;
cin.getline(p,n);
cout<<p<<endl;
cout<<p;
return 0;
}
Upvotes: 0
Views: 2767
Reputation: 678
When you press enter you have to take care of the extra char that is also fed to cin.getline() If that is taken care of it will work fine. This is the behavior of cin in Windows. May happen same in Linux. If you run this code in Windows it will give you what you want.
#include <iostream>
using namespace std;
int main () {
int n;
// Take number of chars
cout<<"Number of chars in string: ";
cin>>n;
// Take the string in dynamic char array
char *pStr = new char[n+1];
cout<<"Enter your string: "<<endl;
// Feed extra char
char tCh;
cin.get(tCh);
// Store until newline
cin.getline(pStr, n+1);
cout<<"You entered: "<<pStr<<endl;
// Free memory like gentle-man
delete []pStr;
// Bye bye
return 0;
}
HTH!
Upvotes: 0
Reputation: 103
You need to read chars from stdin until you meet some terminator (newline for example) and append that char to the end of your temporary char array (char*). For all this you should manually control overflows and extend (reallocate+copy) array as necessary.
Upvotes: 0
Reputation: 10947
Use getline.
Take a look a this example:
http://www.cplusplus.com/reference/iostream/istream/getline/
Upvotes: 2