input the numbers of characters in a string

I was trying to resolve this activity with differents methods but I feel that I 'm so closing.
thank you


the Out put expected is

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




other test

number of character :-10
allocation failure!

the code is :


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

int count(string);

int main()
{
string str;
 int num ;

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

return 0;
}
Last edited on
I believe you want something like this:
1
2
3
4
5
6
7
if( num > 1 ) {
    while( str.length( ) < num ) {
        cout << "Enter text: ";
        getline( cin, str );
    }
    cout << "Text: " << str << '\n';
}
Thank you integraft, for your answer, your the best!!!!
,that´s runnig.
just I have other question .what I need to change to my program stop just in the number of characters that the user have inputted.
for example:
if If 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!

Exp: Text: Hi\n
Thank you.
Have a look at string's member function subtr().
http://www.cplusplus.com/reference/string/string/substr/
To get a string containing the first 2 characters from the original string.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

int main()
{
    std::string str = "Word";

    // 0 is where to start copying from
    // 2 is how many characters to copy to
    std::cout << str.substr(0, 2) << '\n';

    return 0;
}
Last edited on
Thank you!!!!!!!!
It works perfect!!!!
Topic archived. No new replies allowed.