promp the number of character for the user in a string

Nov 28, 2016 at 4:15am
Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 #include<iostream>
#include<string>
using namespace std;

int count(string);

int main()
{
string str;
 int num;

cout << "Number of characters: ";
cin >> num;

if (num > 1){
cout << "Enter text: " ;
getline(cin,str);
cout << "Text: " << str.size(num);}
else 
	cout << "Allocation failure!";


return 0;
}


the Out put expected is

number of characters: 13
enter tex: nospaceshere!
text: nospaceshere!




other test

number of character :-10
allocation failure!
I was trying to resolve this activity with differents methods but I feel that I 'm so closing.
thank you.
Nov 28, 2016 at 8:52am
What exactly are you trying to do on line 18?

Note that str.size() will return the size of the entered string.
Nov 28, 2016 at 8:49pm
Ok,I could change something from this code....but the thing that I can't do is to limit the string inputted by the user.
for example :
We are allocating space for a 2 character string but the user
is giving us more. We need to stop at two characters

> Number of characters: 2
> Enter Text: Hi Bob!
> Text: Hi Bob!\n
expected:HI
I could run this code using this but,I can limit the string,
thank you for your answer code777,

1
2
3
4
5
6
7
8
9
10
if( num > 1 ){
	
    while( str.length( ) < num ) {
        cout << "Enter text: ";
        getline( cin, str );
    }
	cout << "Text: " << str << '\n';
	

}
Nov 29, 2016 at 5:13am
Thank you I could find the answwer!!
Topic archived. No new replies allowed.