Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fix spacing in copycat program

Tags:

c++

copy

spacing

Here is my code for a basic copycat program that just copys whatever the user types:

#include <iostream>

using namespace std;
#include <string>

int main()
{
    cout << "type something.. I dare you..." << endl;
    for (;;)
    {
        string usrin;
        cout << "You: ";
        cin >> usrin;
        cout << "Me: " << usrin;
    }
    return 0;
}

But when the user inputs more than one word i get this:

Me: more

You: than

You: Me: one

You: Me: word

You:

any and all help is appreciated! thank you!

like image 743
theChef613 Avatar asked Mar 21 '26 04:03

theChef613


1 Answers

You need to use cin.getline(usrin) instead of cin >> usrin.

cin >> usrin stops reading when it finds whitespace characters in the stream but leaves the rest of the stream for the next time cin is used.

cin.getline will read until the end of the line. However, you will need to change usrin to an array of char.

char usrln[MAX_LINE_LENGTH];

where MAX_LINE_LENGTH is a constant that is bigger than the length of the longest line you expect to see.

like image 149
R Sahu Avatar answered Mar 23 '26 01:03

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!